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.09.22'

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}.'''

77 notOverloaded(self, underOK=True)

78

79 @Property_RO

80 def ellipsoid(self):

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

82 '''

83 return self._E

84

85 @Property_RO

86 def _e_option(self):

87 E = self.ellipsoid

88 if E is _EWGS84:

89 return () # default

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

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

92

93 @property

94 def Exact(self):

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

96 '''

97 return self._Exact

98

99 @Exact.setter # PYCHOK setter!

100 def Exact(self, Exact):

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

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

103 '''

104 Exact = bool(Exact)

105 if self._Exact != Exact:

106 _update_all(self)

107 self._Exact = Exact

108

109 @Property_RO

110 def flattening(self):

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

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

113 '''

114 return self.ellipsoid.f

115

116 f = flattening

117

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

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

120 '''

121 N = len(Names)

122 if N < 1:

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

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

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

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

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

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

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

130 n += Names

131 else:

132 n, v = Names, t

133 if self.verbose: # PYCHOK no cover

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

135 if floats:

136 v = map(float, v)

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

138 return self._iter2tion(r, r)

139

140 @property_RO

141 def invokation(self):

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

143 '''

144 return self._invokation

145

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

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

148

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

150 options (C{str}s).

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

152

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

154

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

156 code from C{GeodSolve}.

157

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

159 from C{RhumbSolve}.

160

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

162 '''

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

164 i = _xkwds_get(stdin, stdin=None)

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

166 s = self.status

167 if s:

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

169 txt=_not_(_0_))

170 if self.verbose: # PYCHOK no cover

171 self._print(r)

172 return r

173

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

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

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

177 '''

178 self._invokation += 1

179 self._status = t = None

180 if self.verbose: # PYCHOK no cover

181 t = _cmd_stdin_(cmd, stdin)

182 self._print(t)

183 try: # invoke and write to stdin

184 s, r = _popen2(cmd, stdin)

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

186 raise ValueError(r)

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

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

189 self._status = s

190 return r

191

192 @Property_RO

193 def _mpd(self): # meter per degree

194 return self.ellipsoid._Lpd

195

196 @property_RO

197 def _p_option(self):

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

199

200 @Property

201 def prec(self):

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

203 '''

204 return self._prec

205

206 @prec.setter # PYCHOK setter!

207 def prec(self, prec):

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

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

210

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

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

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

214 '''

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

216 if self._prec != prec:

217 _update_all(self)

218 self._prec = prec

219

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

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

222 '''

223 if self.status is not None:

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

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

226

227 @Property

228 def reverse2(self):

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

230 '''

231 return self._reverse2

232

233 @reverse2.setter # PYCHOK setter!

234 def reverse2(self, reverse2):

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

236 '''

237 reverse2 = bool(reverse2)

238 if self._reverse2 != reverse2:

239 _update_all(self)

240 self._reverse2 = reverse2

241

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

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

244 '''

245 hold = self._Solve_path

246 if hold != path:

247 _update_all(self)

248 self._Solve_path = path

249 try:

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

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

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

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

254 hold = path

255 finally: # restore in case of error

256 if self._Solve_path != hold:

257 _update_all(self)

258 self._Solve_path = hold

259

260 @property_RO

261 def status(self):

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

263 or C{None}.

264 '''

265 return self._status

266

267 @Property

268 def unroll(self):

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

270 '''

271 return self._unroll

272

273 @unroll.setter # PYCHOK setter!

274 def unroll(self, unroll):

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

276 '''

277 unroll = bool(unroll)

278 if self._unroll != unroll:

279 _update_all(self)

280 self._unroll = unroll

281

282 @property

283 def verbose(self):

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

285 '''

286 return self._verbose

287

288 @verbose.setter # PYCHOK setter!

289 def verbose(self, verbose):

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

291 a message around each C{RhumbSolve} invokation.

292 '''

293 self._verbose = bool(verbose)

294

295 @Property_RO

296 def version(self):

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

298 '''

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

300

301

302 class _SolveBase(_SolveLineSolveBase):

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

304 '''

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

306 '''New C{Solve} instance.

307

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

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

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

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

312 is specified as C{scalar}.

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

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

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

316

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

318 '''

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

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

321 if name:

322 self.name = name

323 if path:

324 self._setSolve(path)

325

326 @Property_RO

327 def _cmdDirect(self):

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

329 '''

330 return self._cmdBasic

331

332 @Property_RO

333 def _cmdInverse(self):

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

335 '''

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

337

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

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

340 '''

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

342

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

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

345 '''

346 if arcmode:

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

348 floats = _xkwds_get(floats, floats=True)

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

350 lat, lon, azi, s12_a12)

351

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

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

354 I{without} C{_SALPs_CALPs_}.

355 '''

356 floats = _xkwds_get(floats, floats=True)

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

358 lat1, lon1, lat2, lon2)

359

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

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

362 '''

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

364

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

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

367 '''

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

369 # and .HeightIDWkarney._distances

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

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

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

373 return abs(float(r.a12))

374

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

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

377 '''

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

379 status=self.status, **Solve)

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

381

382

383 class _SolveLineBase(_SolveLineSolveBase):

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

385 '''

386# _caps = 0

387# _lla1 = {}

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

389

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

391 self._caps = caps | Caps._LINE

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

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

394 self._solve = solve

395

396 n = name or solve.name

397 if n:

398 self.name = n

399

400 @Property_RO

401 def _cmdDistance(self):

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

403 '''

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

405 _, azi = azi.popitem()

406 return lat1, lon1, azi

407

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

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

410

411 @property_RO

412 def ellipsoid(self):

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

414 '''

415 return self._solve.ellipsoid

416

417 @Property_RO

418 def lat1(self):

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

420 '''

421 return self._lla1.lat1

422

423 @Property_RO

424 def lon1(self):

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

426 '''

427 return self._lla1.lon1

428

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

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

431 '''

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

433 lat1=self.lat1, lon1=self.lon1,

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

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

436

437

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

439

440# **) MIT License

441#

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

443#

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

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

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

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

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

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

450#

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

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

453#

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

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

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

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

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

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

460# OTHER DEALINGS IN THE SOFTWARE.