Coverage for pygeodesy/solveBase.py: 95%

208 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-09-20 13:43 -0400

1 

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

3 

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

5''' 

6 

7from pygeodesy.basics import map2, ub2str, _zip 

8from pygeodesy.constants import DIG 

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

10from pygeodesy.errors import _AssertionError, _xkwds_get 

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

12 _EQUAL_, _Error_, _not_, _SPACE_, _UNUSED_ 

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

14 Precision_, _EWGS84 

15from pygeodesy.lazily import _ALL_DOCS, printf, _sys_version_info2 

16from pygeodesy.named import callername, notOverloaded 

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

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

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

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

21 

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

23 

24__all__ = () # nothing public 

25__version__ = '23.09.18' 

26 

27_ERROR_ = 'ERROR' 

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

29 

30 

31def _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 

39def _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 

51class _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 _mpd(self): # meter per degree 

195 return self.ellipsoid._Lpd 

196 

197 @property_RO 

198 def _p_option(self): 

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

200 

201 @Property 

202 def prec(self): 

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

204 ''' 

205 return self._prec 

206 

207 @prec.setter # PYCHOK setter! 

208 def prec(self, prec): 

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

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

211 

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

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

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

215 ''' 

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

217 if self._prec != prec: 

218 _update_all(self) 

219 self._prec = prec 

220 

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

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

223 ''' 

224 if self.status is not None: 

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

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

227 

228 @Property 

229 def reverse2(self): 

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

231 ''' 

232 return self._reverse2 

233 

234 @reverse2.setter # PYCHOK setter! 

235 def reverse2(self, reverse2): 

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

237 ''' 

238 reverse2 = bool(reverse2) 

239 if self._reverse2 != reverse2: 

240 _update_all(self) 

241 self._reverse2 = reverse2 

242 

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

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

245 ''' 

246 hold = self._Solve_path 

247 if hold != path: 

248 _update_all(self) 

249 self._Solve_path = path 

250 try: 

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

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

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

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

255 hold = path 

256 finally: # restore in case of error 

257 if self._Solve_path != hold: 

258 _update_all(self) 

259 self._Solve_path = hold 

260 

261 @property_RO 

262 def status(self): 

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

264 or C{None}. 

265 ''' 

266 return self._status 

267 

268 @Property 

269 def unroll(self): 

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

271 ''' 

272 return self._unroll 

273 

274 @unroll.setter # PYCHOK setter! 

275 def unroll(self, unroll): 

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

277 ''' 

278 unroll = bool(unroll) 

279 if self._unroll != unroll: 

280 _update_all(self) 

281 self._unroll = unroll 

282 

283 @property 

284 def verbose(self): 

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

286 ''' 

287 return self._verbose 

288 

289 @verbose.setter # PYCHOK setter! 

290 def verbose(self, verbose): 

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

292 a message around each C{RhumbSolve} invokation. 

293 ''' 

294 self._verbose = bool(verbose) 

295 

296 @Property_RO 

297 def version(self): 

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

299 ''' 

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

301 

302 

303class _SolveBase(_SolveLineSolveBase): 

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

305 ''' 

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

307 '''New C{Solve} instance. 

308 

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

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

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

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

313 is specified as C{scalar}. 

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

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

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

317 

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

319 ''' 

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

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

322 if name: 

323 self.name = name 

324 if path: 

325 self._setSolve(path) 

326 

327 @Property_RO 

328 def _cmdDirect(self): 

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

330 ''' 

331 return self._cmdBasic 

332 

333 @Property_RO 

334 def _cmdInverse(self): 

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

336 ''' 

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

338 

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

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

341 ''' 

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

343 

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

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

346 ''' 

347 if arcmode: 

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

349 floats = _xkwds_get(floats, floats=True) 

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

351 lat, lon, azi, s12_a12) 

352 

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

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

355 I{without} C{_SALPs_CALPs_}. 

356 ''' 

357 floats = _xkwds_get(floats, floats=True) 

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

359 lat1, lon1, lat2, lon2) 

360 

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

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

363 ''' 

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

365 

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

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

368 ''' 

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

370 # and .HeightIDWkarney._distances 

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

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

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

374 return abs(float(r.a12)) 

375 

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

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

378 ''' 

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

380 status=self.status, **Solve) 

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

382 

383 

384class _SolveLineBase(_SolveLineSolveBase): 

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

386 ''' 

387# _caps = 0 

388# _lla1 = {} 

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

390 

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

392 self._caps = caps | Caps._LINE 

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

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

395 self._solve = solve 

396 

397 n = name or solve.name 

398 if n: 

399 self.name = n 

400 

401 @Property_RO 

402 def _cmdDistance(self): 

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

404 ''' 

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

406 _, azi = azi.popitem() 

407 return lat1, lon1, azi 

408 

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

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

411 

412 @property_RO 

413 def ellipsoid(self): 

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

415 ''' 

416 return self._solve.ellipsoid 

417 

418 @Property_RO 

419 def lat1(self): 

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

421 ''' 

422 return self._lla1.lat1 

423 

424 @Property_RO 

425 def lon1(self): 

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

427 ''' 

428 return self._lla1.lon1 

429 

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

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

432 ''' 

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

434 lat1=self.lat1, lon1=self.lon1, 

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

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

437 

438 

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

440 

441# **) MIT License 

442# 

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

444# 

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

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

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

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

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

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

451# 

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

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

454# 

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

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

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

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

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

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

461# OTHER DEALINGS IN THE SOFTWARE.