1

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

3

4 u'''Wrapper around several C{geomath.Math} functions from I{Karney}'s Python package

5 U{geographiclib<https://PyPI.org/project/geographiclib>}, provided that package is installed.

6

7 The I{wrapped} class methods return a L{GDict} instance offering access to the C{dict} items

8 either by C{key} or by C{attribute} name.

9

10 With env variable C{PYGEODESY_GEOGRAPHICLIB} left undefined or set to C{"2"}, this module,

11 L{pygeodesy.geodesicw} and L{pygeodesy.geodesicx} will use U{GeographicLib 2.0

12<https://GeographicLib.SourceForge.io/C++/doc/>} and newer transcoding, otherwise C{1.52}

13 or older.

14

15 Karney-based functionality

16==========================

17

18 1. The following classes and functions in C{pygeodesy}

19

20 - L{AlbersEqualArea}, L{AlbersEqualArea2}, L{AlbersEqualArea4},

21 L{AlbersEqualAreaCylindrical}, L{AlbersEqualAreaNorth}, L{AlbersEqualAreaSouth} --

22 U{AlbersEqualArea<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1AlbersEqualArea.html>}

23

24 - L{AuxAngle}, L{AuxDST}, L{AuxDLat}, L{AuxLat} -- U{AuxAngle

25 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1AuxAngle.html>},

26 U{DST<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1DST.html>},

27 U{DAuxLatitude<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1DAuxLatitude.html>},

28 U{AuxLatitude<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1AuxLatitude.html>} in I{GeographicLib 2.2+}

29

30 - L{CassiniSoldner} -- U{CassiniSoldner<https://GeographicLib.SourceForge.io/C++/doc/

31 classGeographicLib_1_1CassiniSoldner.html>}

32

33 - L{EcefKarney} -- U{Geocentric<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Geocentric.html>}

34

35 - L{Elliptic} -- U{EllipticFunction<https://GeographicLib.SourceForge.io/C++/doc/

36 classGeographicLib_1_1EllipticFunction.html>}

37

38 - L{EquidistantExact}, L{EquidistantGeodSolve}, L{EquidistantKarney} -- U{AzimuthalEquidistant

39 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1AzimuthalEquidistant.html>}

40

41 - L{Etm}, L{ExactTransverseMercator} -- U{TransverseMercatorExact

42 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1TransverseMercatorExact.html>}

43

44 - L{Geodesic}, L{GeodesicLine} -- I{wrapped} U{geodesic.Geodesic<https://PyPI.org/project/geographiclib>},

45 I{wrapped} U{geodesicline.GeodesicLine<https://PyPI.org/project/geographiclib>}

46

47 - L{GeodesicAreaExact}, L{PolygonArea} -- U{PolygonArea<https://GeographicLib.SourceForge.io/C++/doc/

48 classGeographicLib_1_1PolygonAreaT.html>}

49

50 - L{GeodesicExact}, L{GeodesicLineExact} -- U{GeodesicExact<https://GeographicLib.SourceForge.io/C++/doc/

51 classGeographicLib_1_1GeodesicExact.html>}, U{GeodesicLineExact<https://GeographicLib.SourceForge.io/C++/doc/

52 classGeographicLib_1_1GeodesicLineExact.html>}

53

54 - L{GeoidKarney} -- U{Geoid<https://GeographicLib.SourceForge.io/C++/doc/geoid.html>}

55

56 - L{Georef} -- U{Georef<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Georef.html>}

57

58 - L{GnomonicExact}, L{GnomonicGeodSolve}, L{GnomonicKarney} -- U{Gnomonic

59 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Gnomonic.html>}

60

61 - L{JacobiConformal} -- U{JacobiConformal

62 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1JacobiConformal.html#details>}

63

64 - L{KTransverseMercator} - U{TransverseMercator

65 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1TransverseMercator.html>}

66

67 - L{LocalCartesian}, L{Ltp} -- U{LocalCartesian<https://GeographicLib.SourceForge.io/C++/doc/

68 classGeographicLib_1_1LocalCartesian.html>}

69

70 - L{Osgr} -- U{OSGB<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1OSGB.html>}

71

72 - L{rhumbaux}, L{RhumbAux}, L{RhumbLineAux} -- U{Rhumb

73 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Rhumb.html>} and U{RhumbLine

74 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1RhumbLine.html>} from I{GeographicLib 2.2+}

75

76 - L{rhumbx}, L{Rhumb}, L{RhumbLine} -- U{Rhumb

77 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Rhumb.html>},

78 U{RhumbLine<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1RhumbLine.html>},

79 U{TransverseMercator<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1TransverseMercator.html>}

80 from I{GeographicLib 2.0}

81

82 - L{Ups} -- U{PolarStereographic<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1PolarStereographic.html>}

83

84 - L{Utm} -- U{TransverseMercator<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1TransverseMercator.html>}

85

86 - L{UtmUps}, L{Epsg} -- U{UTMUPS<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1UTMUPS.html>}

87

88 - L{pygeodesy.atan1d}, L{pygeodesy.atan2d}, L{pygeodesy.sincos2}, L{pygeodesy.sincos2d}, L{pygeodesy.tand} -- U{geomath.Math

89 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Math.html>}

90

91 are I{transcoded} from C++ classes in I{Karney}'s U{GeographicLib<https://GeographicLib.SourceForge.io/C++/doc/annotated.html>}.

92

93 2. These C{pygeodesy} modules and classes

94

95 - L{ellipsoidalGeodSolve}, L{ellipsoidalKarney}, L{geodsolve}, L{karney}, L{rhumbsolve}

96 - L{EquidistantKarney}, L{FrechetKarney}, L{GeodesicSolve}, L{GeodesicLineSolve}, L{GnomonicGeodSolve},

97 L{GnomonicKarney}, L{HeightIDWkarney}

98

99 are or use I{wrappers} around I{Karney}'s Python U{geographiclib<https://PyPI.org/project/geographiclib>}

100 C{geodesic}, C++ utility U{GeodSolve<https://GeographicLib.SourceForge.io/C++/doc/GeodSolve.1.html>} or

101 C++ utility U{RhumbSolve<https://GeographicLib.SourceForge.io/C++/doc/RhumbSolve.1.html>}.

102

103 3. All C{pygeodesy} functions and methods to compute I{ellipsoidal} intersections, nearest points and trilaterations

104

105 - L{ellipsoidalExact.intersection3}, L{ellipsoidalExact.intersections2}, L{ellipsoidalExact.nearestOn},

106 L{ellipsoidalExact.LatLon.intersection3}, L{ellipsoidalExact.LatLon.intersections2},

107 L{ellipsoidalExact.LatLon.nearestOn}, L{ellipsoidalExact.LatLon.trilaterate5}

108

109 - L{ellipsoidalKarney.intersection3}, L{ellipsoidalKarney.intersections2}, L{ellipsoidalKarney.nearestOn},

110 L{ellipsoidalKarney.LatLon.intersection3}, L{ellipsoidalKarney.LatLon.intersections2},

111 L{ellipsoidalKarney.LatLon.nearestOn}, L{ellipsoidalKarney.LatLon.trilaterate5}

112

113 - L{ellipsoidalVincenty.intersection3}, L{ellipsoidalVincenty.intersections2}, L{ellipsoidalVincenty.nearestOn},

114 L{ellipsoidalVincenty.LatLon.intersection3}, L{ellipsoidalVincenty.LatLon.intersections2},

115 L{ellipsoidalVincenty.LatLon.nearestOn}, L{ellipsoidalVincenty.LatLon.trilaterate5}

116

117 - L{RhumbLineAux.intersection2} and L{RhumbLineAux.nearestOn4} C{(exact=None)} in L{rhumbaux} and

118 L{RhumbLine.intersection2} and L{RhumbLine.nearestOn4} C{(exact=None)} in L{rhumbx}

119

120 are implementations of I{Karney}'s iterative solution posted under U{The B{ellipsoidal} case

121<https://GIS.StackExchange.com/questions/48937/calculating-intersection-of-two-circles>} and in paper U{Geodesics

122 on an ellipsoid of revolution<https://ArXiv.org/pdf/1102.1215.pdf>} (pp 20-21, section B{14. MARITIME BOUNDARIES}).

123

124 4. Spherical functions

125

126 - L{pygeodesy.excessKarney_}, L{sphericalTrigonometry.areaOf}

127

128 in C{pygeodesy} are based on I{Karney}'s post U{Area of a spherical polygon

129<https://MathOverflow.net/questions/97711/the-area-of-spherical-polygons>}, 3rd Answer.

130'''

131# make sure int/int division yields float quotient, see .basics

132 from __future__ import division as _; del _ # PYCHOK semicolon

133

134 from pygeodesy.basics import _copysign, int1s, isint, neg, unsigned0, \

135 _xgeographiclib, _xImportError, _xversion_info, \

136 _xinstanceof, _zip, isodd # PYCHOK shared

137 from pygeodesy.constants import NAN, _isfinite as _math_isfinite, _0_0, \

138 _1_16th, _1_0, _2_0, _180_0, _N_180_0, _360_0

139 from pygeodesy.datums import _a_ellipsoid, _EWGS84, _WGS84 # PYCHOK shared

140# from pygeodesy.ellipsoids import _EWGS84 # from .datums

141 from pygeodesy.errors import GeodesicError, itemsorted, _ValueError, _xkwds, \

142 _xkwds_get

143 from pygeodesy.fmath import cbrt, fremainder, hypot as _hypot, norm2, \

144 Fsum, unstr # PYCHOK shared

145# from pygeodesy.fsums import Fsum # from .fmath

146 from pygeodesy.interns import NN, _2_, _a12_, _area_, _azi2_, _azi12_, \

147 _composite_, _lat1_, _lat2_, _lon1_, _lon2_, \

148 _m12_, _M12_, _M21_, _number_, _s12_, _S12_, \

149 _UNDER_, _BAR_ # PYCHOK used!

150 from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS, _getenv

151 from pygeodesy.named import _Dict, _NamedBase, _NamedTuple, notImplemented, _Pass

152 from pygeodesy.props import deprecated_method, Property_RO, property_RO

153# from pygeodesy.streps import unstr # from .fmath

154 from pygeodesy.units import Bearing as _Azi, Degrees as _Deg, Lat, Lon, \

155 Meter as _M, Meter2 as _M2, Number_, \

156 Precision_, _1mm as _TOL_M # PYCHOK shared

157 from pygeodesy.utily import atan2d, sincos2d, tand, _unrollon, fabs

158

159# from math import fabs # from .utily

160

161__all__ = _ALL_LAZY.karney

162__version__ = '23.09.28'

163

164_K_2_0 = _getenv('PYGEODESY_GEOGRAPHICLIB', _2_) == _2_

165_perimeter_ = 'perimeter'

166

167

168 class _GTuple(_NamedTuple): # in .testNamedTuples

169 '''(INTERNAL) Helper.

170 '''

171 def toGDict(self, **updates):

172 '''Convert this C{*Tuple} to a L{GDict}.

173

174 @kwarg updates: Optional items to apply (C{nam=value} pairs)

175 '''

176 r = GDict(_zip(self._Names_, self)) # strict=True

177 if updates:

178 r.update(updates)

179 if self._iteration is not None:

180 r._iteration = self._iteration

181 return r

182

183

184 class _Lat(Lat):

185 '''(INTERNAL) Latitude B{C{lat}}.

186 '''

187 def __init__(self, *lat, **Error_name):

188 kwds = _xkwds(Error_name, clip=0, Error=GeodesicError)

189 Lat.__new__(_Lat, *lat, **kwds)

190

191

192 class _Lon(Lon):

193 '''(INTERNAL) Longitude B{C{lon}}.

194 '''

195 def __init__(self, *lon, **Error_name):

196 kwds = _xkwds(Error_name, clip=0, Error=GeodesicError)

197 Lon.__new__(_Lon, *lon, **kwds)

198

199

200 class Area3Tuple(_NamedTuple): # in .geodesicx.gxarea

201 '''3-Tuple C{(number, perimeter, area)} with the C{number}

202 of points on the polygon or polyline, the C{perimeter} in

203 C{meter} and the C{area} in C{meter} I{squared}.

204 '''

205 _Names_ = (_number_, _perimeter_, _area_)

206 _Units_ = ( Number_, _M, _M2)

207

208

209 class Caps(object): # PYCHOK

210 '''(INTERNAL) Overriden by C{Caps} below.

211 '''

212 EMPTY = 0 # formerly aka NONE

213 _CAP_1 = 1 << 0 # for goedesicw only

214 _CAP_1p = 1 << 1 # for goedesicw only

215# _CAP_2 = 1 << 2

216 _CAP_3 = 1 << 3 # for goedesicw only

217# _CAP_4 = 1 << 4

218# _CAP_ALL = 0x1F

219# _CAP_MASK = _CAP_ALL

220 LATITUDE = 1 << 7 # compute latitude C{lat2}

221 LONGITUDE = 1 << 8 # compute longitude C{lon2} _CAP_3

222 AZIMUTH = 1 << 9 # azimuths C{azi1} and C{azi2}

223 DISTANCE = 1 << 10 # compute distance C{s12} _CAP_1

224 DISTANCE_IN = 1 << 11 # allow distance C{s12} in Direct _CAP_1 | _CAP_1p

225 REDUCEDLENGTH = 1 << 12 # compute reduced length C{m12} _CAP_1 | _CAP_2

226 GEODESICSCALE = 1 << 13 # compute geodesic scales C{M12} and C{M21} _CAP_1 | _CAP_2

227 AREA = 1 << 14 # compute area C{S12} _CAP_4

228

229 STANDARD = AZIMUTH | DISTANCE | DISTANCE_IN | LATITUDE | LONGITUDE

230 ALL = 0x7F80 # without LONG_UNROLL, LINE_OFF, REVERSE2 and _DEBUG_*

231

232 _DIRECT3 = AZIMUTH | LATITUDE | LONGITUDE | _CAP_3 # for goedesicw only

233 _INVERSE3 = AZIMUTH | DISTANCE | _CAP_1 # for goedesicw only

234 _STD = STANDARD | _CAP_3 | _CAP_1 # for goedesicw only

235 _STD_LINE = _STD | _CAP_1p # for goedesicw only

236

237 LINE_OFF = 1 << 15 # Line without updates from parent geodesic or rhumb

238 LONG_UNROLL = 1 << 16 # unroll C{lon2} in .Direct and .Position

239 REVERSE2 = 1 << 17 # reverse C{azi2}

240

241 LATITUDE_LONGITUDE = LATITUDE | LONGITUDE

242 LATITUDE_LONGITUDE_AREA = LATITUDE | LONGITUDE | AREA

243

244 AZIMUTH_DISTANCE = AZIMUTH | DISTANCE

245 AZIMUTH_DISTANCE_AREA = AZIMUTH | DISTANCE | AREA

246

247 _ANGLE_ONLY = 1 << 18 # angular distance C{a12} only

248 _SALPs_CALPs = 1 << 19 # (INTERNAL) GeodesicExact._GenInverse

249

250 _DEBUG_AREA = 1 << 20 # (INTERNAL) include Line details

251 _DEBUG_DIRECT = 1 << 21 # (INTERNAL) include Direct details

252 _DEBUG_INVERSE = 1 << 22 # (INTERNAL) include Inverse details

253 _DEBUG_LINE = 1 << 23 # (INTERNAL) include Line details

254 _DEBUG_ALL = _DEBUG_AREA | _DEBUG_DIRECT | _DEBUG_INVERSE | \

255 _DEBUG_LINE | _ANGLE_ONLY | _SALPs_CALPs

256

257 _OUT_ALL = ALL

258 _OUT_MASK = ALL | LONG_UNROLL | REVERSE2 | _DEBUG_ALL

259

260 _AZIMUTH_LATITUDE_LONGITUDE = AZIMUTH | LATITUDE | LONGITUDE

261 _DEBUG_DIRECT_LINE = _DEBUG_DIRECT | _DEBUG_LINE

262# _DISTANCE_IN_OUT = DISTANCE_IN & _OUT_MASK # == DISTANCE_IN in .gx, .gxline

263 _LINE = AZIMUTH | LATITUDE | LONG_UNROLL

264 _REDUCEDLENGTH_GEODESICSCALE = REDUCEDLENGTH | GEODESICSCALE

265# _REDUCEDLENGTH_GEODESICSCALE_DISTANCE = REDUCEDLENGTH | GEODESICSCALE | DISTANCE

266

267 def toStr(self, Csk, sep=_BAR_):

268 '''Return a C{Caps} or C{outmask} as C{str} or tuple of C{str}s.

269 '''

270 s = []

271 for c, C in itemsorted(self.__class__.__dict__):

272 if isint(C) and (Csk & C) and int1s(C) == 1 \

273 and (C in (Caps.REVERSE2, Caps._SALPs_CALPs)

274 or c.replace(_UNDER_, NN).isupper()):

275 s.append(c)

276 return sep.join(s) if sep else tuple(s)

277

278 Caps = Caps() # PYCHOK singleton

279'''I{Enum}-style masks to be bit-C{or}'ed to specify geodesic or

280 rhumb capabilities (C{caps}) and expected results (C{outmask}).

281

282 C{AREA} - compute area C{S12},

283

284 C{AZIMUTH} - include azimuths C{azi1} and C{azi2},

285

286 C{DISTANCE} - compute distance C{s12},

287

288 C{DISTANCE_IN} - allow distance C{s12} in C{.Direct},

289

290 C{EMPTY} - nothing, formerly aka C{NONE},

291

292 C{GEODESICSCALE} - compute geodesic scales C{M12} and C{M21},

293

294 C{LATITUDE} - compute latitude C{lat2},

295

296 C{LINE_OFF} - Line without updates from parent geodesic or rhumb.

297

298 C{LONGITUDE} - compute longitude C{lon2},

299

300 C{LONG_UNROLL} - unroll C{lon2} in C{.Direct},

301

302 C{REDUCEDLENGTH} - compute reduced length C{m12},

303

304 C{REVERSE2} - reverse C{azi2},

305

306 and C{ALL} - all of the above.

307

308 C{STANDARD} = C{AZIMUTH | DISTANCE | DISTANCE_IN | LATITUDE | LONGITUDE}'''

309

310

311 class _CapsBase(_NamedBase): # in .auxilats, .geodesicx.gxbases

312 '''(INTERNAL) Base class for C{[_]Geodesic*Exact}.

313 '''

314 ALL = Caps.ALL

315 AREA = Caps.AREA

316 AZIMUTH = Caps.AZIMUTH

317 DISTANCE = Caps.DISTANCE

318 DISTANCE_IN = Caps.DISTANCE_IN

319 EMPTY = Caps.EMPTY # aka NONE

320 GEODESICSCALE = Caps.GEODESICSCALE

321 LATITUDE = Caps.LATITUDE

322 LINE_OFF = Caps.LINE_OFF

323 LONGITUDE = Caps.LONGITUDE

324 LONG_UNROLL = Caps.LONG_UNROLL

325 REDUCEDLENGTH = Caps.REDUCEDLENGTH

326 STANDARD = Caps.STANDARD

327

328 _caps = 0 # None

329 _debug = 0 # or Caps._DEBUG_...

330

331 @Property_RO

332 def caps(self):

333 '''Get the capabilities (bit-or'ed C{Caps}).

334 '''

335 return self._caps

336

337 def caps_(self, caps):

338 '''Check the available capabilities.

339

340 @arg caps: Bit-or'ed combination of L{Caps} values

341 for all capabilities to be checked.

342

343 @return: C{True} if I{all} B{C{caps}} are available,

344 C{False} otherwise (C{bool}).

345 '''

346 caps &= Caps._OUT_ALL

347 return (self.caps & caps) == caps

348

349 @property

350 def debug(self):

351 '''Get the C{debug} option (C{bool}).

352 '''

353 return bool(self._debug)

354

355 @debug.setter # PYCHOK setter!

356 def debug(self, debug):

357 '''Set the C{debug} option (C{bool}) to include

358 more details in L{GDict} results.

359 '''

360 self._debug = Caps._DEBUG_ALL if debug else 0

361

362 def _iter2tion(self, r, s):

363 '''(INTERNAL) Copy C{C{s}.iter} into C{B{r}._iteration}.

364 '''

365 i = _xkwds_get(s, iter=None)

366 if i is not None:

367 self._iteration = r._iteration = i

368 return r

369

370

371 class Direct9Tuple(_GTuple):

372 '''9-Tuple C{(a12, lat2, lon2, azi2, s12, m12, M12, M21, S12)} with arc

373 length C{a12}, angles C{lat2}, C{lon2} and azimuth C{azi2} in C{degrees},

374 distance C{s12} and reduced length C{m12} in C{meter} and area C{S12} in

375 C{meter} I{squared}.

376 '''

377 _Names_ = (_a12_, _lat2_, _lon2_, _azi2_, _s12_, _m12_, _M12_, _M21_, _S12_)

378 _Units_ = (_Azi, _Lat, _Lon, _Azi, _M, _Pass, _Pass, _Pass, _M2)

379

380

381 class GDict(_Dict): # XXX _NamedDict

382 '''Basic C{dict} with both key I{and} attribute access

383 to the C{dict} items.

384

385 Results of all C{geodesic} methods are returned as a

386 L{GDict} instance.

387 '''

388 _iteration = None # Iteration number (C{int}) or C{None}

389

390 @property_RO

391 def iteration(self): # see .named._NamedBase

392 '''Get the iteration number (C{int}) or

393 C{None} if not available/applicable.

394 '''

395 return self._iteration

396

397 def toDirect9Tuple(self, dflt=NAN):

398 '''Convert this L{GDict} result to a 9-tuple, like I{Karney}'s

399 method C{geographiclib.geodesic.Geodesic._GenDirect}.

400

401 @kwarg dflt: Default value for missing items (C{any}).

402

403 @return: L{Direct9Tuple}C{(a12, lat2, lon2, azi2,

404 s12, m12, M12, M21, S12)}

405 '''

406 return self._toTuple(Direct9Tuple, dflt)

407

408 def toGeodSolve12Tuple(self, dflt=NAN): # PYCHOK 12 args

409 '''Convert this L{GDict} result to a 12-Tuple, compatible with I{Karney}'s

410 U{GeodSolve<https://GeographicLib.SourceForge.io/C++/doc/GeodSolve.1.html>}

411 result.

412

413 @kwarg dflt: Default value for missing items (C{any}).

414

415 @return: L{GeodSolve12Tuple}C{(lat1, lon1, azi1, lat2, lon2, azi2,

416 s12, a12, m12, M12, M21, S12)}.

417 '''

418 return self._toTuple(_MODS.geodsolve.GeodSolve12Tuple, dflt)

419

420 def toInverse10Tuple(self, dflt=NAN):

421 '''Convert this L{GDict} result to a 10-tuple, like I{Karney}'s

422 method C{geographiclib.geodesic.Geodesic._GenInverse}.

423

424 @kwarg dflt: Default value for missing items (C{any}).

425

426 @return: L{Inverse10Tuple}C{(a12, s12, salp1, calp1,

427 salp2, calp2, m12, M12, M21, S12)}.

428 '''

429 return self._toTuple(Inverse10Tuple, dflt)

430

431 @deprecated_method

432 def toRhumb7Tuple(self, dflt=NAN): # PYCHOK no cover

433 '''DEPRECATED, used method C{toRhumb8Tuple}.

434

435 @return: A I{DEPRECATED} L{Rhumb7Tuple}.

436 '''

437 return self._toTuple(_MODS.deprecated.Rhumb7Tuple, dflt)

438

439 def toRhumb8Tuple(self, dflt=NAN):

440 '''Convert this L{GDict} result to a 8-tuple.

441

442 @kwarg dflt: Default value for missing items (C{any}).

443

444 @return: L{Rhumb8Tuple}C{(lat1, lon1, lat2, lon2,

445 azi12, s12, S12, a12)}.

446 '''

447 return self._toTuple(Rhumb8Tuple, dflt)

448

449 def toRhumbSolve7Tuple(self, dflt=NAN):

450 '''Convert this L{GDict} result to a 8-tuple.

451

452 @kwarg dflt: Default value for missing items (C{any}).

453

454 @return: L{RhumbSolve7Tuple}C{(lat1, lon1, lat2, lon2,

455 azi12, s12, S12)}.

456 '''

457 return self._toTuple(_MODS.rhumbsolve.RhumbSolve7Tuple, dflt)

458

459 def _toTuple(self, nTuple, dflt):

460 '''(INTERNAL) Convert this C{GDict} to an B{C{nTuple}}.

461 '''

462 _g = getattr

463 t = tuple(_g(self, n, dflt) for n in nTuple._Names_)

464 return nTuple(t, iteration=self._iteration)

465

466

467 class Inverse10Tuple(_GTuple):

468 '''10-Tuple C{(a12, s12, salp1, calp1, salp2, calp2, m12, M12, M21, S12)} with arc length

469 C{a12} in C{degrees}, distance C{s12} and reduced length C{m12} in C{meter}, area

470 C{S12} in C{meter} I{squared} and the sines C{salp1}, C{salp2} and cosines C{calp1},

471 C{calp2} of the initial C{1} and final C{2} foward azimuths.

472 '''

473 _Names_ = (_a12_, _s12_, 'salp1', 'calp1', 'salp2', 'calp2', _m12_, _M12_, _M21_, _S12_)

474 _Units_ = (_Azi, _M, _Pass, _Pass, _Pass, _Pass, _Pass, _Pass, _Pass, _M2)

475

476 def toGDict(self, **updates):

477 '''Convert this C{Inverse10Tuple} to a L{GDict}.

478

479 @kwarg updates: Optional items to apply (C{nam=value} pairs)

480 '''

481 return _GTuple.toGDict(self, azi1=atan2d(self.salp1, self.calp1), # PYCHOK indent, namedTuple

482 azi2=atan2d(self.salp2, self.calp2), # PYCHOK namedTuple

483 **updates) # PYCHOK indent

484

485

486 class _kWrapped(object): # in .geodesicw

487 ''''(INTERNAL) Wrapper for some of I{Karney}'s U{geographiclib

488 <https://PyPI.org/project/geographiclib>} classes.

489 '''

490

491 @Property_RO

492 def geographiclib(self):

493 '''Get the imported C{geographiclib}, provided the U{geographiclib

494 <https://PyPI.org/project/geographiclib>} package is installed,

495 otherwise an C{ImportError}.

496 '''

497 g = _xgeographiclib(self.__class__, 1, 49)

498 from geographiclib.geodesic import Geodesic

499 g.Geodesic = Geodesic

500 from geographiclib.geodesicline import GeodesicLine

501 g.GeodesicLine = GeodesicLine

502 from geographiclib.geomath import Math

503 g.Math = Math

504 return g

505

506 @Property_RO # MCCABE 13

507 def Math(self):

508 '''Wrap the C{geomath.Math} class, provided the U{geographiclib

509 <https://PyPI.org/project/geographiclib>} package is installed,

510 otherwise C{None}.

511 '''

512 try:

513 g = self.geographiclib

514 M = g.Math

515 if _xversion_info(g) < (2,):

516 if _K_2_0:

517 M = None

518# elif not _K_2_0: # XXX set 2.0?

519# _K_2_0 = True

520 except (AttributeError, ImportError):

521 M = None

522 return M

523

524_wrapped = _kWrapped() # PYCHOK singleton, .datum, .test/base.py

525

526

527 class Rhumb8Tuple(_GTuple):

528 '''8-Tuple C{(lat1, lon1, lat2, lon2, azi12, s12, S12, a12)} with lat- C{lat1},

529 C{lat2} and longitudes C{lon1}, C{lon2} of both points, the azimuth of the

530 rhumb line C{azi12}, the distance C{s12}, the area C{S12} under the rhumb

531 line and the angular distance C{a12} between both points.

532 '''

533 _Names_ = (_lat1_, _lon1_, _lat2_, _lon2_, _azi12_, _s12_, _S12_, _a12_)

534 _Units_ = ( Lat, Lon, Lat, Lon, _Azi, _M, _M2, _Deg)

535

536 def toDirect9Tuple(self, dflt=NAN, **a12_azi1_azi2_m12_M12_M21):

537 '''Convert this L{Rhumb8Tuple} result to a 9-tuple, like I{Karney}'s

538 method C{geographiclib.geodesic.Geodesic._GenDirect}.

539

540 @kwarg dflt: Default value for missing items (C{any}).

541 @kwarg a12_azi1_azi2_m12_M12_M21: Optional keyword arguments

542 to specify or override L{Inverse10Tuple} items.

543

544 @return: L{Direct9Tuple}C{(a12, lat2, lon2, azi2, s12,

545 m12, M12, M21, S12)}

546 '''

547 d = dict(azi1=self.azi12, M12=_1_0, m12=self.s12, # PYCHOK attr

548 azi2=self.azi12, M21=_1_0) # PYCHOK attr

549 if a12_azi1_azi2_m12_M12_M21:

550 d.update(a12_azi1_azi2_m12_M12_M21)

551 return self._toTuple(Direct9Tuple, dflt, d)

552

553 def toInverse10Tuple(self, dflt=NAN, **a12_m12_M12_M21_salp1_calp1_salp2_calp2):

554 '''Convert this L{Rhumb8Tuple} to a 10-tuple, like I{Karney}'s

555 method C{geographiclib.geodesic.Geodesic._GenInverse}.

556

557 @kwarg dflt: Default value for missing items (C{any}).

558 @kwarg a12_m12_M12_M21_salp1_calp1_salp2_calp2: Optional keyword

559 arguments to specify or override L{Inverse10Tuple} items.

560

561 @return: L{Inverse10Tuple}C{(a12, s12, salp1, calp1, salp2, calp2,

562 m12, M12, M21, S12)}.

563 '''

564 s, c = sincos2d(self.azi12) # PYCHOK attr

565 d = dict(salp1=s, calp1=c, M12=_1_0, m12=self.s12, # PYCHOK attr

566 salp2=s, calp2=c, M21=_1_0)

567 if a12_m12_M12_M21_salp1_calp1_salp2_calp2:

568 d.update(a12_m12_M12_M21_salp1_calp1_salp2_calp2)

569 return self._toTuple(Inverse10Tuple, dflt, d)

570

571 def _toTuple(self, nTuple, dflt, updates={}):

572 '''(INTERNAL) Convert this C{Rhumb8Tuple} to an B{C{nTuple}}.

573 '''

574 _g = self.toGDict(**updates).get

575 t = tuple(_g(n, dflt) for n in nTuple._Names_)

576 return nTuple(t, name=self.name)

577

578 @deprecated_method

579 def _to7Tuple(self):

580 '''DEPRECATED, do not use!'''

581 return _MODS.deprecated.Rhumb7Tuple(self[:-1])

582

583

584 def _around(x): # in .utily.sincos2d

585 '''I{Coarsen} a scalar by rounding small values to underflow to C{0.0}.

586

587 @return: Coarsened value (C{float}).

588

589 @see: I{Karney}'s U{geomath.Math.AngRound<https://SourceForge.net/p/

590 geographiclib/code/ci/release/tree/python/geographiclib/geomath.py>}

591 '''

592 try:

593 return _wrapped.Math.AngRound(x)

594 except AttributeError:

595 if x:

596 y = _1_16th - fabs(x)

597 if y > 0: # fabs(x) < _1_16th

598 x = _copysign(_1_16th - y, x)

599 else:

600 x = _0_0 # -0 to 0

601 return x

602

603

604 def _atan2d(y, x):

605 '''Return C{atan2(B{y}, B{x})} in C{degrees}.

606 '''

607 try:

608 return _wrapped.Math.atan2d(y, x)

609 except AttributeError:

610 return atan2d(y, x)

611

612

613 def _cbrt(x):

614 '''Return C{cubic root(B{x})}.

615 '''

616 try:

617 return _wrapped.Math.cbrt(x)

618 except AttributeError:

619 return cbrt(x)

620

621

622 def _copyBit(x, y):

623 '''Like C{copysign0(B{x}, B{y})}, with C{B{x} > 0}.

624 '''

625 return (-x) if _signBit(y) else x

626

627

628 def _2cos2x(cx, sx): # in .auxDST, .auxLat, .gxbases

629 '''Return M{2 * cos(2 * x)} from cos(x) and sin(x).

630 '''

631 r = cx - sx

632 if r:

633 r *= (cx + sx) * _2_0

634 return r

635

636

637 def _diff182(deg0, deg, K_2_0=False):

638 '''Compute C{deg - deg0}, reduced to C{[-180,180]} accurately.

639

640 @return: 2-Tuple C{(delta_angle, residual)} in C{degrees}.

641 '''

642 try:

643 return _wrapped.Math.AngDiff(deg0, deg)

644 except AttributeError:

645 if K_2_0 or _K_2_0: # geographiclib 2.0

646 _r, _360 = fremainder, _360_0

647 d, t = _sum2(_r(-deg0, _360),

648 _r( deg, _360))

649 d, t = _sum2(_r( d, _360), t)

650 if d in (_0_0, _180_0, _N_180_0):

651 d = _copysign(d, -t if t else (deg - deg0))

652 else:

653 _n = _norm180

654 d, t = _sum2(_n(-deg0), _n(deg))

655 d = _n(d)

656 if t > 0 and d == _180_0:

657 d = _N_180_0

658 d, t = _sum2(d, t)

659 return d, t

660

661

662 def _fix90(deg): # mimick Math.LatFix

663 '''Replace angle in C{degrees} outside [-90,90] by NAN.

664

665 @return: Angle C{degrees} or NAN.

666 '''

667 try:

668 return _wrapped.Math.LatFix(deg)

669 except AttributeError:

670 return NAN if fabs(deg) > 90 else deg

671

672

673 def _isfinite(x): # mimick geomath.Math.isfinite

674 '''Check finiteness of C{x}.

675

676 @return: C{True} if finite.

677 '''

678 try:

679 return _wrapped.Math.isfinite(x)

680 except AttributeError:

681 return _math_isfinite(x) # and fabs(x) <= _MAX

682

683

684 def _norm2(x, y): # mimick geomath.Math.norm

685 '''Normalize C{B{x}} and C{B{y}}.

686

687 @return: 2-Tuple of C{(B{x}, B{y})}, normalized.

688 '''

689 try:

690 return _wrapped.Math.norm(x, y)

691 except AttributeError:

692 return norm2(x, y)

693

694

695 def _norm180(deg): # mimick geomath.Math.AngNormalize

696 '''Reduce angle in C{degrees} to (-180,180].

697

698 @return: Reduced angle C{degrees}.

699 '''

700 try:

701 return _wrapped.Math.AngNormalize(deg)

702 except AttributeError:

703 d = fremainder(deg, _360_0)

704 if d in (_180_0, _N_180_0):

705 d = _copysign(_180_0, deg) if _K_2_0 else _180_0

706 return d

707

708

709 def _polygon(geodesic, points, closed, line, wrap):

710 '''(INTERNAL) Compute the area or perimeter of a polygon,

711 using a L{GeodesicExact}, L{GeodesicSolve} or (if the

712 C{geographiclib} package is installed) a C{Geodesic}

713 or C{geodesicw.Geodesic} instance.

714 '''

715 if not wrap: # capability LONG_UNROLL can't be off

716 notImplemented(None, wrap=wrap, up=3)

717

718 if _MODS.booleans.isBoolean(points):

719 # recursive call for each boolean clip

720

721 def _a_p(clip, *args, **unused):

722 return _polygon(geodesic, clip, *args)

723

724 if not closed: # closed only

725 raise _ValueError(closed=closed, points=_composite_)

726

727 return points._sum1(_a_p, closed, line, wrap)

728

729 gP = geodesic.Polygon(line)

730 _A = gP.AddPoint

731

732 Ps = _MODS.iters.PointsIter(points, loop=1, wrap=wrap) # base=LatLonEllipsoidalBase(0, 0)

733 p1 = p0 = Ps[0]

734

735 # note, lon deltas are unrolled, by default

736 _A(p1.lat, p1.lon)

737 for p2 in Ps.iterate(closed=closed):

738 if wrap and not Ps.looped:

739 p2 = _unrollon(p1, p2)

740 _A(p2.lat, p2.lon)

741 p1 = p2

742 if closed and line and p1 != p0:

743 _A(p0.lat, p0.lon)

744

745 # gP.Compute returns (number_of_points, perimeter, signed area)

746 return gP.Compute(False, True)[1 if line else 2]

747

748

749 def _polynomial(x, cs, i, j): # PYCHOK shared

750 '''(INTERNAL) Like C++ C{GeographicLib.Math.hpp.polyval} but with a

751 different signature and cascaded summation as C{karney._sum2_}.

752

753 @return: M{sum(cs[k] * x**(j - k - 1) for k in range(i, j)}

754 '''

755 # assert 0 <= i <= j <= len(cs)

756# try:

757# return _wrapped.Math.polyval(j - i - 1, cs, i, x)

758# except AttributeError:

759# pass

760 s, t = cs[i], _0_0

761 for c in cs[i+1:j]:

762 s, t = _sum2_(s * x, t * x, c)

763 return s # + t

764

765

766 def _remainder(x, y):

767 '''Remainder of C{x / y}.

768

769 @return: Remainder in the range M{[-y / 2, y / 2]}, preserving signed 0.0.

770 '''

771 try:

772 return _wrapped.Math.remainder(x, y)

773 except AttributeError:

774 return fremainder(x, y)

775

776

777 if _K_2_0:

778 from math import cos as _cos, sin as _sin

779

780 def _sincos2(rad):

781 return _sin(rad), _cos(rad)

782

783 _signBit = _MODS.basics.signBit

784 else:

785 _sincos2 = _MODS.utily.sincos2 # PYCHOK shared

786

787 def _signBit(x):

788 '''(INTERNAL) GeographicLib 1.52-.

789 '''

790 return x < 0

791

792

793 def _sincos2d(deg):

794 '''Return sine and cosine of an angle in C{degrees}.

795

796 @return: 2-Tuple C{(sin(B{deg}), cos(B{deg}))}.

797 '''

798 try:

799 return _wrapped.Math.sincosd(deg)

800 except AttributeError:

801 return sincos2d(deg)

802

803

804 def _sincos2de(deg, t):

805 '''Return sine and cosine of a corrected angle in C{degrees}.

806

807 @return: 2-Tuple C{(sin(B{deg}), cos(B{deg}))}.

808 '''

809 try:

810 return _wrapped.Math.sincosde(deg, t)

811 except AttributeError:

812 return sincos2d(deg, adeg=t)

813

814

815 def _sum2(u, v): # mimick geomath.Math.sum, actually sum2

816 '''Error-free summation like C{geomath.Math.sum}.

817

818 @return: 2-Tuple C{(B{u} + B{v}, residual)}.

819

820 @note: The C{residual} can be the same as B{C{u}} or B{C{v}}.

821

822 @see: U{Algorithm 3.1<https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}.

823 '''

824 try:

825 return _wrapped.Math.sum(u, v)

826 except AttributeError:

827 s = u + v

828 r = s - v

829 t = s - r

830 # if Algorithm_3_1:

831 # t = (u - t) + (v + r)

832 # elif C_CPP: # Math::sum C/C++

833 # r -= u

834 # t -= v

835 # t += r

836 # t = -t

837 # else:

838 t = (u - r) + (v - t)

839 return s, t

840

841

842 def _sum2_(s, t, *vs):

843 '''Accumulate any B{C{vs}} into a previous C{_sum2(s, t)}.

844

845 @return: 2-Tuple C{(B{s} + B{t} + sum(B{vs}), residual)}.

846

847 @see: I{Karney's} C++ U{Accumulator<https://GeographicLib.SourceForge.io/

848 html/Accumulator_8hpp_source.html>} comments for more details and

849 function C{_sum2} above.

850

851 @note: NOT "error-free", see C{pygeodesy.test/testKarney.py}.

852 '''

853 _s2, _u0 = _sum2, unsigned0

854 for v in vs:

855 if v:

856 t, u = _s2(t, v) # start at the least-

857 if s:

858 s, t = _s2(s, t) # significant end

859 if s:

860 t += u # accumulate u into t

861# elif t: # s == 0 implies t == 0

862# raise _AssertionError(t=t, txt=_not_(_0_))

863 else:

864 s = _u0(u) # result is u, t = 0

865 else:

866 s, t = _u0(t), u

867 return s, t

868

869

870 def _tand(x):

871 '''Return C{tan(B{x})} in C{degrees}.

872 '''

873 try:

874 return _wrapped.Math.tand(x)

875 except AttributeError:

876 return tand(x)

877

878

879 def _unroll2(lon1, lon2, wrap=False): # see .ellipsoidalBaseDI._intersects2

880 '''Unroll B{C{lon2 - lon1}} like C{geodesic.Geodesic.Inverse}.

881

882 @return: 2-Tuple C{(B{lon2} - B{lon1}, B{lon2})} with B{C{lon2}}

883 unrolled if B{C{wrap}} is C{True}, normalized otherwise.

884 '''

885 if wrap:

886 d, t = _diff182(lon1, lon2)

887 lon2, _ = _sum2_(d, t, lon1) # (lon1 + d) + t

888 else:

889 lon2 = _norm180(lon2)

890 return (lon2 - lon1), lon2

891

892

893 def _unsigned2(x):

894 '''(INTERNAL) Unsign B{C{x}}.

895 '''

896 return (neg(x), True) if _signBit(x) else (x, False)

897

898

899__all__ += _ALL_DOCS(_CapsBase)

900

901# **) MIT License

902#

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

904#

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

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

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

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

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

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

911#

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

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

914#

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

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

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

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

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

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

921# OTHER DEALINGS IN THE SOFTWARE.