1

2# -*- coding: utf-8 -*-

3

4 u'''(INTERNAL) Private base classes for L{pygeodesy.geodsolve} and L{pygeodesy.rhumbsolve}.

5'''

6

7 from pygeodesy.basics import map2, ub2str, _zip

8 from pygeodesy.constants import DIG

9# from pygeodesy.ellipsoids import _EWGS84 # from .karney

10 from pygeodesy.errors import _AssertionError, _xkwds_get

11 from pygeodesy.interns import NN, _0_, _BACKSLASH_, _COMMASPACE_, _enquote, \

12 _EQUAL_, _Error_, _not_, _SPACE_, _UNUSED_

13 from pygeodesy.karney import Caps, _CapsBase, _a_ellipsoid, GDict, \

14 Precision_, _EWGS84

15 from pygeodesy.lazily import _ALL_DOCS, printf, _sys_version_info2

16 from pygeodesy.named import callername, notOverloaded

17 from pygeodesy.props import Property, Property_RO, property_RO, _update_all

18 from pygeodesy.streprs import Fmt, fstr, fstrzs, pairs, strs

19# from pygeodesy.units import Precision_ # from .karney

20 from pygeodesy.utily import unroll180, wrap360 # PYCHOK shared

21

22 from subprocess import PIPE as _PIPE, Popen as _Popen, STDOUT as _STDOUT

23

24__all__ = () # nothing public

25__version__ = '23.08.20'

26

27_ERROR_ = 'ERROR'

28_text_True = dict() if _sys_version_info2 < (3, 7) else dict(text=True)

29

30

31 def _cmd_stdin_(cmd, stdin): # PYCHOK no cover

32 '''(INTERNAL) Cmd line, stdin and caller as sC{str}.

33 '''

34 c = Fmt.PAREN(callername(up=3))

35 t = (c,) if stdin is None else (_BACKSLASH_, str(stdin), c)

36 return _SPACE_.join(cmd + t)

37

38

39 def _popen2(cmd, stdin=None): # in .mgrs, .test.base, .test.testMgrs

40 '''(INTERNAL) Invoke C{B{cmd} tuple} and return C{exitcode}

41 and all output to C{stdout/-err}.

42 '''

43 p = _Popen(cmd, creationflags=0,

44 # executable=sys.executable, shell=True,

45 stdin=_PIPE, stdout=_PIPE, stderr=_STDOUT,

46 **_text_True) # PYCHOK kwArgs

47 r = p.communicate(stdin)[0]

48 return p.returncode, ub2str(r).strip()

49

50

51 class _SolveLineSolveBase(_CapsBase):

52 '''(NTERNAL) Base class for C{_Solve} and C{_LineSolve}.

53 '''

54 _E = _EWGS84

55 _Error = None

56 _Exact = True

57 _invokation = 0

58 _Names_Direct = \

59 _Names_Inverse = ()

60 _prec = Precision_(prec=DIG)

61 _reverse2 = False

62 _Solve_name = NN # executable basename

63 _Solve_path = NN # executable path

64 _status = None

65 _unroll = False

66 _verbose = False

67

68 @Property_RO

69 def a(self):

70 '''Get the I{equatorial} radius, semi-axis (C{meter}).

71 '''

72 return self.ellipsoid.a

73

74 @property_RO

75 def _cmdBasic(self): # PYCHOK no cover

76 '''(INTERNAL) I{Must be overloaded}, see function C{notOverloaded}.

77 '''

78 notOverloaded(self)

79

80 @Property_RO

81 def ellipsoid(self):

82 '''Get the ellipsoid (C{Ellipsoid}).

83 '''

84 return self._E

85

86 @Property_RO

87 def _e_option(self):

88 E = self.ellipsoid

89 if E is _EWGS84:

90 return () # default

91 a, f = strs(E.a_f, fmt=Fmt.F, prec=DIG + 3) # not .G!

92 return ('-e', a, f)

93

94 @property

95 def Exact(self):

96 '''Get the Solve's C{exact} setting (C{bool}).

97 '''

98 return self._Exact

99

100 @Exact.setter # PYCHOK setter!

101 def Exact(self, Exact):

102 '''Set the Solve's C{exact} setting (C{bool}),

103 if C{True} use I{exact} version.

104 '''

105 Exact = bool(Exact)

106 if self._Exact != Exact:

107 _update_all(self)

108 self._Exact = Exact

109

110 @Property_RO

111 def flattening(self):

112 '''Get the C{ellipsoid}'s I{flattening} (C{scalar}), M{(a - b) / a},

113 C{0} for spherical, negative for prolate.

114 '''

115 return self.ellipsoid.f

116

117 f = flattening

118

119 def _GDictInvoke(self, cmd, floats, Names, *args):

120 '''(INTERNAL) Invoke C{Solve}, return results as C{GDict}.

121 '''

122 N = len(Names)

123 if N < 1:

124 raise _AssertionError(cmd=cmd, Names=Names)

125 i = fstr(args, prec=DIG, fmt=Fmt.F, sep=_SPACE_) if args else None # not Fmt.G!

126 t = self._invoke(cmd, stdin=i).lstrip().split() # 12-/+ tuple

127 if len(t) > N: # PYCHOK no cover

128 # unzip instrumented name=value pairs to names and values

129 n, v = _zip(*(p.split(_EQUAL_) for p in t[:-N])) # strict=True

130 v += tuple(t[-N:])

131 n += Names

132 else:

133 n, v = Names, t

134 if self.verbose: # PYCHOK no cover

135 self._print(_COMMASPACE_.join(map(Fmt.EQUAL, n, map(fstrzs, v))))

136 if floats:

137 v = map(float, v)

138 r = GDict(_zip(n, v)) # strict=True

139 return self._iter2tion(r, r)

140

141 @property_RO

142 def invokation(self):

143 '''Get the most recent C{Solve} invokation number (C{int}).

144 '''

145 return self._invokation

146

147 def invoke(self, *options, **stdin):

148 '''Invoke the C{Solve} executable and return the result.

149

150 @arg options: No, one or several C{Solve} command line

151 options (C{str}s).

152 @kwarg stdin: Optional input to pass to C{Solve.stdin} (C{str}).

153

154 @return: The C{Solve.stdout} and C{.stderr} output (C{str}).

155

156 @raise GeodesicError: On any error, including a non-zero return

157 code from C{GeodSolve}.

158

159 @raise RhumbError: On any error, including a non-zero return code

160 from C{RhumbSolve}.

161

162 @note: The C{Solve} return code is in property L{status}.

163 '''

164 c = (self._Solve_path,) + map2(str, options)

165 i = _xkwds_get(stdin, stdin=None)

166 r = self._invoke(c, stdin=i)

167 s = self.status

168 if s:

169 raise self._Error(cmd=_cmd_stdin_(c, i), status=s,

170 txt=_not_(_0_))

171 if self.verbose: # PYCHOK no cover

172 self._print(r)

173 return r

174

175 def _invoke(self, cmd, stdin=None):

176 '''(INTERNAL) Invoke the C{Solve} executable, with the

177 given B{C{cmd}} line and optional input to B{C{stdin}}.

178 '''

179 self._invokation += 1

180 self._status = t = None

181 if self.verbose: # PYCHOK no cover

182 t = _cmd_stdin_(cmd, stdin)

183 self._print(t)

184 try: # invoke and write to stdin

185 s, r = _popen2(cmd, stdin)

186 if len(r) < 6 or r[:5] in (_Error_, _ERROR_):

187 raise ValueError(r)

188 except (IOError, OSError, TypeError, ValueError) as x:

189 raise self._Error(cmd=t or _cmd_stdin_(cmd, stdin), cause=x)

190 self._status = s

191 return r

192

193 @property_RO

194 def _p_option(self):

195 return '-p', str(self.prec - 5) # -p is distance prec

196

197 @Property

198 def prec(self):

199 '''Get the precision, number of (decimal) digits (C{int}).

200 '''

201 return self._prec

202

203 @prec.setter # PYCHOK setter!

204 def prec(self, prec):

205 '''Set the precision for C{angles} in C{degrees}, like C{lat}, C{lon},

206 C{azimuth} and C{arc} in number of decimal digits (C{int}, C{0}..L{DIG}).

207

208 @note: The precision for C{distance = B{prec} - 5} or up to

209 10 decimal digits for C{nanometer} and for C{area =

210 B{prec} - 12} or at most C{millimeter} I{squared}.

211 '''

212 prec = Precision_(prec=prec, high=DIG)

213 if self._prec != prec:

214 _update_all(self)

215 self._prec = prec

216

217 def _print(self, line): # PYCHOK no cover

218 '''(INTERNAL) Print a status line.

219 '''

220 if self.status is not None:

221 line = _SPACE_(line, Fmt.PAREN(self.status))

222 printf('%s %d: %s', self.named2, self.invokation, line)

223

224 @Property

225 def reverse2(self):

226 '''Get the C{azi2} direction (C{bool}).

227 '''

228 return self._reverse2

229

230 @reverse2.setter # PYCHOK setter!

231 def reverse2(self, reverse2):

232 '''Set the direction for C{azi2} (C{bool}), if C{True} reverse C{azi2}.

233 '''

234 reverse2 = bool(reverse2)

235 if self._reverse2 != reverse2:

236 _update_all(self)

237 self._reverse2 = reverse2

238

239 def _setSolve(self, path, **Solve_path):

240 '''(INTERNAL) Set the executable C{path}.

241 '''

242 hold = self._Solve_path

243 if hold != path:

244 _update_all(self)

245 self._Solve_path = path

246 try:

247 _ = self.version # test path and ...

248 if self.status: # ... return code

249 S_p = Solve_path or {self._Solve_name: _enquote(path)}

250 raise self._Error(status=self.status, txt=_not_(_0_), **S_p)

251 hold = path

252 finally: # restore in case of error

253 if self._Solve_path != hold:

254 _update_all(self)

255 self._Solve_path = hold

256

257 @property_RO

258 def status(self):

259 '''Get the most recent C{Solve} return code (C{int}, C{str})

260 or C{None}.

261 '''

262 return self._status

263

264 @Property

265 def unroll(self):

266 '''Get the C{lon2} unroll'ing (C{bool}).

267 '''

268 return self._unroll

269

270 @unroll.setter # PYCHOK setter!

271 def unroll(self, unroll):

272 '''Set unroll'ing for C{lon2} (C{bool}), if C{True} unroll C{lon2}, otherwise don't.

273 '''

274 unroll = bool(unroll)

275 if self._unroll != unroll:

276 _update_all(self)

277 self._unroll = unroll

278

279 @property

280 def verbose(self):

281 '''Get the C{verbose} option (C{bool}).

282 '''

283 return self._verbose

284

285 @verbose.setter # PYCHOK setter!

286 def verbose(self, verbose):

287 '''Set the C{verbose} option (C{bool}), C{True} prints

288 a message around each C{RhumbSolve} invokation.

289 '''

290 self._verbose = bool(verbose)

291

292 @Property_RO

293 def version(self):

294 '''Get the result of C{"GeodSolve --version"} or C{"RhumbSolve --version"}.

295 '''

296 return self.invoke('--version')

297

298

299 class _SolveBase(_SolveLineSolveBase):

300 '''(NTERNAL) Base class for C{_GeodesicSolveBase} and C{_RhumbSolveBase}.

301 '''

302 def __init__(self, a_ellipsoid=_EWGS84, f=None, path=NN, name=NN):

303 '''New C{Solve} instance.

304

305 @arg a_ellipsoid: An ellipsoid (L{Ellipsoid}) or datum (L{Datum}) or

306 the equatorial radius of the ellipsoid (C{scalar},

307 conventionally in C{meter}), see B{C{f}}.

308 @arg f: The flattening of the ellipsoid (C{scalar}) if B{C{a_ellipsoid}}

309 is specified as C{scalar}.

310 @kwarg path: Optionally, the (fully qualified) path to the C{GeodSolve}

311 or C{RhumbSolve} executable (C{filename}).

312 @kwarg name: Optional name (C{str}).

313

314 @raise TypeError: Invalid B{C{a_ellipsoid}} or B{C{f}}.

315 '''

316 if a_ellipsoid not in (self._E, None): # NOT self.ellipsoid

317 self._E = _a_ellipsoid(a_ellipsoid, f, name=name)

318 if name:

319 self.name = name

320 if path:

321 self._setSolve(path)

322

323 @Property_RO

324 def _cmdDirect(self):

325 '''(INTERNAL) Get the C{Solve} I{Direct} cmd (C{tuple}).

326 '''

327 return self._cmdBasic

328

329 @Property_RO

330 def _cmdInverse(self):

331 '''(INTERNAL) Get the C{Solve} I{Inverse} cmd (C{tuple}).

332 '''

333 return self._cmdBasic + ('-i',)

334

335 def Direct(self, lat1, lon1, azi1, s12, outmask=_UNUSED_): # PYCHOK unused

336 '''Return the C{Direct} result.

337 '''

338 return self._GDictDirect(lat1, lon1, azi1, False, s12)

339

340 def _GDictDirect(self, lat, lon, azi, arcmode, s12_a12, outmask=_UNUSED_, **floats): # PYCHOK for .geodesicx.gxarea

341 '''(INTERNAL) Get C{_GenDirect}-like result as C{GDict}.

342 '''

343 if arcmode:

344 raise self._Error(arcmode=arcmode, txt=str(NotImplemented))

345 floats = _xkwds_get(floats, floats=True)

346 return self._GDictInvoke(self._cmdDirect, floats, self._Names_Direct,

347 lat, lon, azi, s12_a12)

348

349 def _GDictInverse(self, lat1, lon1, lat2, lon2, outmask=_UNUSED_, **floats): # PYCHOK for .geodesicx.gxarea

350 '''(INTERNAL) Get C{_GenInverse}-like result as C{GDict}, but

351 I{without} C{_SALPs_CALPs_}.

352 '''

353 floats = _xkwds_get(floats, floats=True)

354 return self._GDictInvoke(self._cmdInverse, floats, self._Names_Inverse,

355 lat1, lon1, lat2, lon2)

356

357 def Inverse(self, lat1, lon1, lat2, lon2, outmask=_UNUSED_): # PYCHOK unused

358 '''Return the C{Inverse} result.

359 '''

360 return self._GDictInverse(lat1, lon1, lat2, lon2)

361

362 def Inverse1(self, lat1, lon1, lat2, lon2, wrap=False):

363 '''Return the non-negative, I{angular} distance in C{degrees}.

364 '''

365 # see .FrechetKarney.distance, .HausdorffKarney._distance

366 # and .HeightIDWkarney._distances

367 _, lon2 = unroll180(lon1, lon2, wrap=wrap) # self.LONG_UNROLL

368 r = self._GDictInverse(lat1, lon1, lat2, lon2, floats=False)

369 # XXX self.DISTANCE needed for 'a12'?

370 return abs(float(r.a12))

371

372 def _toStr(self, prec=6, sep=_COMMASPACE_, **Solve): # PYCHOK signature

373 '''(INTERNAL) Return this C{_Solve} as string..

374 '''

375 d = dict(ellipsoid=self.ellipsoid, invokation=self.invokation,

376 status=self.status, **Solve)

377 return sep.join(pairs(d, prec=prec))

378

379

380 class _SolveLineBase(_SolveLineSolveBase):

381 '''(NTERNAL) Base class for C{GeodesicLineSolve} and C{RhumbLineSolve}.

382 '''

383# _caps = 0

384# _lla1 = {}

385 _solve = None # L{GeodesicSolve} or L{RhumbSolve} instance

386

387 def __init__(self, solve, lat1, lon1, caps, name, **azi):

388 self._caps = caps | Caps._LINE

389 self._debug = solve._debug & Caps._DEBUG_ALL

390 self._lla1 = GDict(lat1=lat1, lon1=lon1, **azi)

391 self._solve = solve

392

393 n = name or solve.name

394 if n:

395 self.name = n

396

397 @Property_RO

398 def _cmdDistance(self):

399 '''(INTERNAL) Get the C{GeodSolve} I{-L} cmd (C{tuple}).

400 '''

401 def _lla3(lat1=0, lon1=0, **azi):

402 _, azi = azi.popitem()

403 return lat1, lon1, azi

404

405 t = strs(_lla3(**self._lla1), prec=DIG, fmt=Fmt.F) # self._solve.prec

406 return self._cmdBasic + ('-L',) + t

407

408 @property_RO

409 def ellipsoid(self):

410 '''Get the ellipsoid (C{Ellipsoid}).

411 '''

412 return self._solve.ellipsoid

413

414 @Property_RO

415 def lat1(self):

416 '''Get the latitude of the first point (C{degrees}).

417 '''

418 return self._lla1.lat1

419

420 @Property_RO

421 def lon1(self):

422 '''Get the longitude of the first point (C{degrees}).

423 '''

424 return self._lla1.lon1

425

426 def _toStr(self, prec=6, sep=_COMMASPACE_, **solve): # PYCHOK signature

427 '''(INTERNAL) Return this C{_LineSolve} as string..

428 '''

429 d = dict(ellipsoid=self.ellipsoid, invokation=self._solve.invokation,

430 lat1=self.lat1, lon1=self.lon1,

431 status=self._solve.status, **solve)

432 return sep.join(pairs(d, prec=prec))

433

434

435__all__ += _ALL_DOCS(_SolveBase, _SolveLineBase, _SolveLineSolveBase)

436

437# **) MIT License

438#

439# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved.

440#

441# Permission is hereby granted, free of charge, to any person obtaining a

442# copy of this software and associated documentation files (the "Software"),

443# to deal in the Software without restriction, including without limitation

444# the rights to use, copy, modify, merge, publish, distribute, sublicense,

445# and/or sell copies of the Software, and to permit persons to whom the

446# Software is furnished to do so, subject to the following conditions:

447#

448# The above copyright notice and this permission notice shall be included

449# in all copies or substantial portions of the Software.

450#

451# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS

452# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

453# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL

454# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR

455# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,

456# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR

457# OTHER DEALINGS IN THE SOFTWARE.