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 f(self):

112 '''Get the ellipsoid's I{flattening} (C{float}), M{(a - b) / a}, C{0} for spherical, negative for prolate.

113 '''

114 return self.ellipsoid.f

115

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

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

118 '''

119 N = len(Names)

120 if N < 1:

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

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

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

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

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

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

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

128 n += Names

129 else:

130 n, v = Names, t

131 if self.verbose: # PYCHOK no cover

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

133 if floats:

134 v = map(float, v)

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

136 return self._iter2tion(r, r)

137

138 @property_RO

139 def invokation(self):

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

141 '''

142 return self._invokation

143

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

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

146

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

148 options (C{str}s).

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

150

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

152

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

154 code from C{GeodSolve}.

155

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

157 from C{RhumbSolve}.

158

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

160 '''

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

162 i = _xkwds_get(stdin, stdin=None)

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

164 s = self.status

165 if s:

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

167 txt=_not_(_0_))

168 if self.verbose: # PYCHOK no cover

169 self._print(r)

170 return r

171

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

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

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

175 '''

176 self._invokation += 1

177 self._status = t = None

178 if self.verbose: # PYCHOK no cover

179 t = _cmd_stdin_(cmd, stdin)

180 self._print(t)

181 try: # invoke and write to stdin

182 s, r = _popen2(cmd, stdin)

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

184 raise ValueError(r)

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

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

187 self._status = s

188 return r

189

190 @property_RO

191 def _p_option(self):

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

193

194 @Property

195 def prec(self):

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

197 '''

198 return self._prec

199

200 @prec.setter # PYCHOK setter!

201 def prec(self, prec):

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

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

204

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

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

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

208 '''

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

210 if self._prec != prec:

211 _update_all(self)

212 self._prec = prec

213

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

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

216 '''

217 if self.status is not None:

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

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

220

221 @Property

222 def reverse2(self):

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

224 '''

225 return self._reverse2

226

227 @reverse2.setter # PYCHOK setter!

228 def reverse2(self, reverse2):

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

230 '''

231 reverse2 = bool(reverse2)

232 if self._reverse2 != reverse2:

233 _update_all(self)

234 self._reverse2 = reverse2

235

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

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

238 '''

239 hold = self._Solve_path

240 if hold != path:

241 _update_all(self)

242 self._Solve_path = path

243 try:

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

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

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

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

248 hold = path

249 finally: # restore in case of error

250 if self._Solve_path != hold:

251 _update_all(self)

252 self._Solve_path = hold

253

254 @property_RO

255 def status(self):

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

257 or C{None}.

258 '''

259 return self._status

260

261 @Property

262 def unroll(self):

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

264 '''

265 return self._unroll

266

267 @unroll.setter # PYCHOK setter!

268 def unroll(self, unroll):

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

270 '''

271 unroll = bool(unroll)

272 if self._unroll != unroll:

273 _update_all(self)

274 self._unroll = unroll

275

276 @property

277 def verbose(self):

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

279 '''

280 return self._verbose

281

282 @verbose.setter # PYCHOK setter!

283 def verbose(self, verbose):

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

285 a message around each C{RhumbSolve} invokation.

286 '''

287 self._verbose = bool(verbose)

288

289 @Property_RO

290 def version(self):

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

292 '''

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

294

295

296 class _SolveBase(_SolveLineSolveBase):

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

298 '''

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

300 '''New C{Solve} instance.

301

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

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

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

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

306 is specified as C{scalar}.

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

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

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

310

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

312 '''

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

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

315 if name:

316 self.name = name

317 if path:

318 self._setSolve(path)

319

320 @Property_RO

321 def _cmdDirect(self):

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

323 '''

324 return self._cmdBasic

325

326 @Property_RO

327 def _cmdInverse(self):

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

329 '''

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

331

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

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

334 '''

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

336

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

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

339 '''

340 if arcmode:

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

342 floats = _xkwds_get(floats, floats=True)

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

344 lat, lon, azi, s12_a12)

345

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

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

348 I{without} C{_SALPs_CALPs_}.

349 '''

350 floats = _xkwds_get(floats, floats=True)

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

352 lat1, lon1, lat2, lon2)

353

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

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

356 '''

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

358

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

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

361 '''

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

363 # and .HeightIDWkarney._distances

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

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

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

367 return abs(float(r.a12))

368

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

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

371 '''

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

373 status=self.status, **Solve)

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

375

376

377 class _SolveLineBase(_SolveLineSolveBase):

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

379 '''

380# _caps = 0

381# _lla1 = {}

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

383

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

385 self._caps = caps | Caps._LINE

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

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

388 self._solve = solve

389

390 n = name or solve.name

391 if n:

392 self.name = n

393

394 @Property_RO

395 def _cmdDistance(self):

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

397 '''

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

399 _, azi = azi.popitem()

400 return lat1, lon1, azi

401

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

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

404

405 @property_RO

406 def ellipsoid(self):

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

408 '''

409 return self._solve.ellipsoid

410

411 @Property_RO

412 def lat1(self):

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

414 '''

415 return self._lla1.lat1

416

417 @Property_RO

418 def lon1(self):

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

420 '''

421 return self._lla1.lon1

422

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

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

425 '''

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

427 lat1=self.lat1, lon1=self.lon1,

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

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

430

431

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

433

434# **) MIT License

435#

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

437#

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

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

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

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

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

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

444#

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

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

447#

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

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

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

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

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

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

454# OTHER DEALINGS IN THE SOFTWARE.