Coverage for pygeodesy/karney.py: 94%
284 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-12-12 14:24 -0500
« prev ^ index » next coverage.py v7.2.2, created at 2023-12-12 14:24 -0500
2# -*- coding: utf-8 -*-
4u'''Wrapper around several C{geomath.Math} functions from I{Karney}'s Python package
5U{geographiclib<https://PyPI.org/project/geographiclib>}, provided that package is installed.
7The I{wrapped} class methods return a L{GDict} instance offering access to the C{dict} items
8either by C{key} or by C{attribute} name.
10With env variable C{PYGEODESY_GEOGRAPHICLIB} left undefined or set to C{"2"}, this module,
11L{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}
13or older.
15Karney-based functionality
16==========================
181. The following classes and functions in C{pygeodesy}
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>}
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+}
30 - L{CassiniSoldner} -- U{CassiniSoldner<https://GeographicLib.SourceForge.io/C++/doc/
31 classGeographicLib_1_1CassiniSoldner.html>}
33 - L{EcefKarney} -- U{Geocentric<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Geocentric.html>}
35 - L{Elliptic} -- U{EllipticFunction<https://GeographicLib.SourceForge.io/C++/doc/
36 classGeographicLib_1_1EllipticFunction.html>}
38 - L{EquidistantExact}, L{EquidistantGeodSolve}, L{EquidistantKarney} -- U{AzimuthalEquidistant
39 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1AzimuthalEquidistant.html>}
41 - L{Etm}, L{ExactTransverseMercator} -- U{TransverseMercatorExact
42 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1TransverseMercatorExact.html>}
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>}
47 - L{GeodesicAreaExact}, L{PolygonArea} -- U{PolygonArea<https://GeographicLib.SourceForge.io/C++/doc/
48 classGeographicLib_1_1PolygonAreaT.html>}
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>}
54 - L{GeoidKarney} -- U{Geoid<https://GeographicLib.SourceForge.io/C++/doc/geoid.html>}
56 - L{Georef} -- U{Georef<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Georef.html>}
58 - L{GnomonicExact}, L{GnomonicGeodSolve}, L{GnomonicKarney} -- U{Gnomonic
59 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Gnomonic.html>}
61 - L{JacobiConformal} -- U{JacobiConformal
62 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1JacobiConformal.html#details>}
64 - L{KTransverseMercator} - U{TransverseMercator
65 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1TransverseMercator.html>}
67 - L{LocalCartesian}, L{Ltp} -- U{LocalCartesian<https://GeographicLib.SourceForge.io/C++/doc/
68 classGeographicLib_1_1LocalCartesian.html>}
70 - L{Osgr} -- U{OSGB<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1OSGB.html>}
72 - L{rhumb.aux_}, 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+}
76 - L{rhumb.ekx}, 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}
82 - L{Ups} -- U{PolarStereographic<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1PolarStereographic.html>}
84 - L{Utm} -- U{TransverseMercator<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1TransverseMercator.html>}
86 - L{UtmUps}, L{Epsg} -- U{UTMUPS<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1UTMUPS.html>}
88 - L{atan1d}, L{atan2d}, L{sincos2}, L{sincos2d}, L{tand} -- U{geomath.Math
89 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Math.html>}
91are I{transcoded} from C++ classes in I{Karney}'s U{GeographicLib<https://GeographicLib.SourceForge.io/C++/doc/annotated.html>}.
932. These C{pygeodesy} modules and classes
95 - L{ellipsoidalGeodSolve}, L{ellipsoidalKarney}, L{geodsolve}, L{karney}, L{rhumb.solve}
96 - L{EquidistantKarney}, L{FrechetKarney}, L{GeodesicSolve}, L{GeodesicLineSolve}, L{GnomonicGeodSolve},
97 L{GnomonicKarney}, L{HeightIDWkarney}
99are or use I{wrappers} around I{Karney}'s Python U{geographiclib<https://PyPI.org/project/geographiclib>}
100C{geodesic}, C++ utility U{GeodSolve<https://GeographicLib.SourceForge.io/C++/doc/GeodSolve.1.html>} or
101C++ utility U{RhumbSolve<https://GeographicLib.SourceForge.io/C++/doc/RhumbSolve.1.html>}.
1033. All C{pygeodesy} functions and methods to compute I{ellipsoidal} intersections, nearest points and trilaterations
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}
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}
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}
117 - L{RhumbLineAux.Intersection} and L{RhumbLine.Intersection}
119are implementations of I{Karney}'s iterative solution posted under U{The B{ellipsoidal} case
120<https://GIS.StackExchange.com/questions/48937/calculating-intersection-of-two-circles>} and in paper U{Geodesics
121on an ellipsoid of revolution<https://ArXiv.org/pdf/1102.1215.pdf>} (pp 20-21, section B{14. MARITIME BOUNDARIES}).
1234. The C{pygeodesy} methods to compute I{ellipsoidal} intersections and nearest points
125 - L{RhumbLineAux.Intersecant2}, L{RhumbLineAux.PlumbTo}, L{RhumbLine.Intersecant2} and L{RhumbLine.PlumbTo}
127are I{transcoded} of I{Karney}'s iterative C++ U{rhumb-intercept
128<https://SourceForge.net/p/geographiclib/discussion/1026620/thread/2ddc295e/>} function.
1305. Spherical functions
132 - L{pygeodesy.excessKarney_}, L{sphericalTrigonometry.areaOf}
134in C{pygeodesy} are based on I{Karney}'s post U{Area of a spherical polygon
135<https://MathOverflow.net/questions/97711/the-area-of-spherical-polygons>}, 3rd Answer.
136'''
137# make sure int/int division yields float quotient, see .basics
138from __future__ import division as _; del _ # PYCHOK semicolon
140from pygeodesy.basics import _copysign, int1s, isint, neg, unsigned0, \
141 _xgeographiclib, _xImportError, _xversion_info, \
142 _xinstanceof, _zip, isodd # PYCHOK shared
143from pygeodesy.constants import NAN, _isfinite as _math_isfinite, _0_0, \
144 _1_16th, _1_0, _2_0, _180_0, _N_180_0, _360_0
145from pygeodesy.errors import GeodesicError, itemsorted, _ValueError, _xkwds, \
146 _xkwds_get
147from pygeodesy.fmath import cbrt, fremainder, hypot as _hypot, norm2, \
148 euclid, Fsum, unstr # PYCHOK shared
149# from pygeodesy.fsums import Fsum # from .fmath
150from pygeodesy.interns import NN, _2_, _a12_, _area_, _azi2_, _azi12_, \
151 _composite_, _lat1_, _lat2_, _lon1_, _lon2_, \
152 _m12_, _M12_, _M21_, _number_, _s12_, _S12_, \
153 _UNDER_, _BAR_ # PYCHOK used!
154from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS, _getenv
155from pygeodesy.named import _Dict, _NamedBase, _NamedTuple, notImplemented, _Pass
156from pygeodesy.props import deprecated_method, Property_RO, property_RO # PYCHOK shared
157# from pygeodesy.streps import unstr # from .fmath
158from pygeodesy.units import Bearing as _Azi, Degrees as _Deg, Lat, Lon, \
159 Meter as _M, Meter2 as _M2, Number_, \
160 Precision_, _1mm as _TOL_M # PYCHOK shared
161from pygeodesy.utily import atan2d, sincos2d, tand, _unrollon, fabs
163# from math import fabs # from .utily
165__all__ = _ALL_LAZY.karney
166__version__ = '23.12.10'
168_K_2_0 = _getenv('PYGEODESY_GEOGRAPHICLIB', _2_) == _2_
169_perimeter_ = 'perimeter'
172class _GTuple(_NamedTuple): # in .testNamedTuples
173 '''(INTERNAL) Helper.
174 '''
175 def toGDict(self, **updates):
176 '''Convert this C{*Tuple} to a L{GDict}.
178 @kwarg updates: Optional items to apply (C{nam=value} pairs)
179 '''
180 r = GDict(_zip(self._Names_, self)) # strict=True
181 if updates:
182 r.update(updates)
183 if self._iteration is not None:
184 r._iteration = self._iteration
185 return r
188class _Lat(Lat):
189 '''(INTERNAL) Latitude B{C{lat}}.
190 '''
191 def __init__(self, *lat, **Error_name):
192 kwds = _xkwds(Error_name, clip=0, Error=GeodesicError)
193 Lat.__new__(_Lat, *lat, **kwds)
196class _Lon(Lon):
197 '''(INTERNAL) Longitude B{C{lon}}.
198 '''
199 def __init__(self, *lon, **Error_name):
200 kwds = _xkwds(Error_name, clip=0, Error=GeodesicError)
201 Lon.__new__(_Lon, *lon, **kwds)
204class Area3Tuple(_NamedTuple): # in .geodesicx.gxarea
205 '''3-Tuple C{(number, perimeter, area)} with the C{number}
206 of points on the polygon or polyline, the C{perimeter} in
207 C{meter} and the C{area} in C{meter} I{squared}.
208 '''
209 _Names_ = (_number_, _perimeter_, _area_)
210 _Units_ = ( Number_, _M, _M2)
213class Caps(object): # PYCHOK
214 '''(INTERNAL) Overriden by C{Caps} below.
215 '''
216 EMPTY = 0 # formerly aka NONE
217 _CAP_1 = 1 << 0 # for goedesicw only
218 _CAP_1p = 1 << 1 # for goedesicw only
219# _CAP_2 = 1 << 2
220 _CAP_3 = 1 << 3 # for goedesicw only
221# _CAP_4 = 1 << 4
222# _CAP_ALL = 0x1F
223# _CAP_MASK = _CAP_ALL
224 LATITUDE = 1 << 7 # compute latitude C{lat2}
225 LONGITUDE = 1 << 8 # compute longitude C{lon2} _CAP_3
226 AZIMUTH = 1 << 9 # azimuths C{azi1} and C{azi2}
227 DISTANCE = 1 << 10 # compute distance C{s12} _CAP_1
228 DISTANCE_IN = 1 << 11 # allow distance C{s12} in Direct _CAP_1 | _CAP_1p
229 REDUCEDLENGTH = 1 << 12 # compute reduced length C{m12} _CAP_1 | _CAP_2
230 GEODESICSCALE = 1 << 13 # compute geodesic scales C{M12} and C{M21} _CAP_1 | _CAP_2
231 AREA = 1 << 14 # compute area C{S12} _CAP_4
233 STANDARD = AZIMUTH | DISTANCE | DISTANCE_IN | LATITUDE | LONGITUDE
234 ALL = 0x7F80 # without LONG_UNROLL, LINE_OFF, REVERSE2 and _DEBUG_*
236 _DIRECT3 = AZIMUTH | LATITUDE | LONGITUDE | _CAP_3 # for goedesicw only
237 _INVERSE3 = AZIMUTH | DISTANCE | _CAP_1 # for goedesicw only
238 _STD = STANDARD | _CAP_3 | _CAP_1 # for goedesicw only
239 _STD_LINE = _STD | _CAP_1p # for goedesicw only
241 LINE_OFF = 1 << 15 # Line without updates from parent geodesic or rhumb
242 LONG_UNROLL = 1 << 16 # unroll C{lon2} in .Direct and .Position
243 REVERSE2 = 1 << 17 # reverse C{azi2}
245 LATITUDE_LONGITUDE = LATITUDE | LONGITUDE
246 LATITUDE_LONGITUDE_AREA = LATITUDE | LONGITUDE | AREA
248 AZIMUTH_DISTANCE = AZIMUTH | DISTANCE
249 AZIMUTH_DISTANCE_AREA = AZIMUTH | DISTANCE | AREA
251 _ANGLE_ONLY = 1 << 18 # angular distance C{a12} only
252 _SALPs_CALPs = 1 << 19 # (INTERNAL) GeodesicExact._GenInverse
254 _DEBUG_AREA = 1 << 20 # (INTERNAL) include Line details
255 _DEBUG_DIRECT = 1 << 21 # (INTERNAL) include Direct details
256 _DEBUG_INVERSE = 1 << 22 # (INTERNAL) include Inverse details
257 _DEBUG_LINE = 1 << 23 # (INTERNAL) include Line details
258 _DEBUG_ALL = _DEBUG_AREA | _DEBUG_DIRECT | _DEBUG_INVERSE | \
259 _DEBUG_LINE | _ANGLE_ONLY | _SALPs_CALPs
261 _OUT_ALL = ALL
262 _OUT_MASK = ALL | LONG_UNROLL | REVERSE2 | _DEBUG_ALL
264 _AZIMUTH_LATITUDE_LONGITUDE = AZIMUTH | LATITUDE | LONGITUDE
265 _DEBUG_DIRECT_LINE = _DEBUG_DIRECT | _DEBUG_LINE
266# _DISTANCE_IN_OUT = DISTANCE_IN & _OUT_MASK # == DISTANCE_IN in .gx, .gxline
267 _LINE = AZIMUTH | LATITUDE | LONG_UNROLL
268 _REDUCEDLENGTH_GEODESICSCALE = REDUCEDLENGTH | GEODESICSCALE
269# _REDUCEDLENGTH_GEODESICSCALE_DISTANCE = REDUCEDLENGTH | GEODESICSCALE | DISTANCE
271 def toStr(self, Csk, sep=_BAR_):
272 '''Return a C{Caps} or C{outmask} as C{str} or tuple of C{str}s.
273 '''
274 s = []
275 for c, C in itemsorted(self.__class__.__dict__):
276 if isint(C) and (Csk & C) and int1s(C) == 1 \
277 and (C in (Caps.REVERSE2, Caps._SALPs_CALPs)
278 or c.replace(_UNDER_, NN).isupper()):
279 s.append(c)
280 return sep.join(s) if sep else tuple(s)
282Caps = Caps() # PYCHOK singleton
283'''I{Enum}-style masks to be bit-C{or}'ed to specify geodesic or
284rhumb capabilities (C{caps}) and expected results (C{outmask}).
286C{AREA} - compute area C{S12},
288C{AZIMUTH} - include azimuths C{azi1} and C{azi2},
290C{DISTANCE} - compute distance C{s12},
292C{DISTANCE_IN} - allow distance C{s12} in C{.Direct},
294C{EMPTY} - nothing, formerly aka C{NONE},
296C{GEODESICSCALE} - compute geodesic scales C{M12} and C{M21},
298C{LATITUDE} - compute latitude C{lat2},
300C{LINE_OFF} - Line without updates from parent geodesic or rhumb.
302C{LONGITUDE} - compute longitude C{lon2},
304C{LONG_UNROLL} - unroll C{lon2} in C{.Direct},
306C{REDUCEDLENGTH} - compute reduced length C{m12},
308C{REVERSE2} - reverse C{azi2},
310and C{ALL} - all of the above.
312C{STANDARD} = C{AZIMUTH | DISTANCE | DISTANCE_IN | LATITUDE | LONGITUDE}'''
315class _CapsBase(_NamedBase): # in .auxilats, .geodesicx.gxbases
316 '''(INTERNAL) Base class for C{[_]Geodesic*Exact}.
317 '''
318 ALL = Caps.ALL
319 AREA = Caps.AREA
320 AZIMUTH = Caps.AZIMUTH
321 DISTANCE = Caps.DISTANCE
322 DISTANCE_IN = Caps.DISTANCE_IN
323 EMPTY = Caps.EMPTY # aka NONE
324 GEODESICSCALE = Caps.GEODESICSCALE
325 LATITUDE = Caps.LATITUDE
326 LINE_OFF = Caps.LINE_OFF
327 LONGITUDE = Caps.LONGITUDE
328 LONG_UNROLL = Caps.LONG_UNROLL
329 REDUCEDLENGTH = Caps.REDUCEDLENGTH
330 STANDARD = Caps.STANDARD
332 _caps = 0 # None
333 _debug = 0 # or Caps._DEBUG_...
335 @Property_RO
336 def caps(self):
337 '''Get the capabilities (bit-or'ed C{Caps}).
338 '''
339 return self._caps
341 def caps_(self, caps):
342 '''Check the available capabilities.
344 @arg caps: Bit-or'ed combination of L{Caps} values
345 for all capabilities to be checked.
347 @return: C{True} if I{all} B{C{caps}} are available,
348 C{False} otherwise (C{bool}).
349 '''
350 caps &= Caps._OUT_ALL
351 return (self.caps & caps) == caps
353 @property
354 def debug(self):
355 '''Get the C{debug} option (C{bool}).
356 '''
357 return bool(self._debug)
359 @debug.setter # PYCHOK setter!
360 def debug(self, debug):
361 '''Set the C{debug} option (C{bool}) to include
362 more details in L{GDict} results.
363 '''
364 self._debug = Caps._DEBUG_ALL if debug else 0
366 def _iter2tion(self, r, s):
367 '''(INTERNAL) Copy C{C{s}.iter} into C{B{r}._iteration}.
368 '''
369 i = _xkwds_get(s, iter=None)
370 if i is not None:
371 self._iteration = r._iteration = i
372 return r
375class Direct9Tuple(_GTuple):
376 '''9-Tuple C{(a12, lat2, lon2, azi2, s12, m12, M12, M21, S12)} with arc
377 length C{a12}, angles C{lat2}, C{lon2} and azimuth C{azi2} in C{degrees},
378 distance C{s12} and reduced length C{m12} in C{meter} and area C{S12} in
379 C{meter} I{squared}.
380 '''
381 _Names_ = (_a12_, _lat2_, _lon2_, _azi2_, _s12_, _m12_, _M12_, _M21_, _S12_)
382 _Units_ = (_Azi, _Lat, _Lon, _Azi, _M, _Pass, _Pass, _Pass, _M2)
385class GDict(_Dict): # XXX _NamedDict
386 '''Basic C{dict} with both key I{and} attribute access
387 to the C{dict} items.
389 Results of all C{geodesic} methods are returned as a
390 L{GDict} instance.
391 '''
392 def toDirect9Tuple(self, dflt=NAN):
393 '''Convert this L{GDict} result to a 9-tuple, like I{Karney}'s
394 method C{geographiclib.geodesic.Geodesic._GenDirect}.
396 @kwarg dflt: Default value for missing items (C{any}).
398 @return: L{Direct9Tuple}C{(a12, lat2, lon2, azi2,
399 s12, m12, M12, M21, S12)}
400 '''
401 return self._toTuple(Direct9Tuple, dflt)
403 def toGeodSolve12Tuple(self, dflt=NAN): # PYCHOK 12 args
404 '''Convert this L{GDict} result to a 12-Tuple, compatible with I{Karney}'s
405 U{GeodSolve<https://GeographicLib.SourceForge.io/C++/doc/GeodSolve.1.html>}
406 result.
408 @kwarg dflt: Default value for missing items (C{any}).
410 @return: L{GeodSolve12Tuple}C{(lat1, lon1, azi1, lat2, lon2, azi2,
411 s12, a12, m12, M12, M21, S12)}.
412 '''
413 return self._toTuple(_MODS.geodsolve.GeodSolve12Tuple, dflt)
415 def toInverse10Tuple(self, dflt=NAN):
416 '''Convert this L{GDict} result to a 10-tuple, like I{Karney}'s
417 method C{geographiclib.geodesic.Geodesic._GenInverse}.
419 @kwarg dflt: Default value for missing items (C{any}).
421 @return: L{Inverse10Tuple}C{(a12, s12, salp1, calp1,
422 salp2, calp2, m12, M12, M21, S12)}.
423 '''
424 return self._toTuple(Inverse10Tuple, dflt)
426 @deprecated_method
427 def toRhumb7Tuple(self, dflt=NAN): # PYCHOK no cover
428 '''DEPRECATED, used method C{toRhumb8Tuple}.
430 @return: A I{DEPRECATED} L{Rhumb7Tuple}.
431 '''
432 return self._toTuple(_MODS.deprecated.classes.Rhumb7Tuple, dflt)
434 def toRhumb8Tuple(self, dflt=NAN):
435 '''Convert this L{GDict} result to a 8-tuple.
437 @kwarg dflt: Default value for missing items (C{any}).
439 @return: L{Rhumb8Tuple}C{(lat1, lon1, lat2, lon2,
440 azi12, s12, S12, a12)}.
441 '''
442 return self._toTuple(Rhumb8Tuple, dflt)
444 def toRhumbSolve7Tuple(self, dflt=NAN):
445 '''Convert this L{GDict} result to a 8-tuple.
447 @kwarg dflt: Default value for missing items (C{any}).
449 @return: L{RhumbSolve7Tuple}C{(lat1, lon1, lat2, lon2,
450 azi12, s12, S12)}.
451 '''
452 return self._toTuple(_MODS.rhumb.solve.RhumbSolve7Tuple, dflt)
454 def _toTuple(self, nTuple, dflt):
455 '''(INTERNAL) Convert this C{GDict} to an B{C{nTuple}}.
456 '''
457 _g = getattr
458 t = tuple(_g(self, n, dflt) for n in nTuple._Names_)
459 return nTuple(t, iteration=self._iteration)
462class Inverse10Tuple(_GTuple):
463 '''10-Tuple C{(a12, s12, salp1, calp1, salp2, calp2, m12, M12, M21, S12)} with arc length
464 C{a12} in C{degrees}, distance C{s12} and reduced length C{m12} in C{meter}, area
465 C{S12} in C{meter} I{squared} and the sines C{salp1}, C{salp2} and cosines C{calp1},
466 C{calp2} of the initial C{1} and final C{2} foward azimuths.
467 '''
468 _Names_ = (_a12_, _s12_, 'salp1', 'calp1', 'salp2', 'calp2', _m12_, _M12_, _M21_, _S12_)
469 _Units_ = (_Azi, _M, _Pass, _Pass, _Pass, _Pass, _Pass, _Pass, _Pass, _M2)
471 def toGDict(self, **updates):
472 '''Convert this C{Inverse10Tuple} to a L{GDict}.
474 @kwarg updates: Optional items to apply (C{nam=value} pairs)
475 '''
476 return _GTuple.toGDict(self, azi1=atan2d(self.salp1, self.calp1), # PYCHOK indent, namedTuple
477 azi2=atan2d(self.salp2, self.calp2), # PYCHOK namedTuple
478 **updates) # PYCHOK indent
481class _kWrapped(object): # in .geodesicw
482 ''''(INTERNAL) Wrapper around I{Karney}'s U{geographiclib
483 <https://PyPI.org/project/geographiclib>}.
484 '''
486 @Property_RO
487 def geographiclib(self):
488 '''Lazily import C{geographiclib}, provided the U{geographiclib
489 <https://PyPI.org/project/geographiclib>} package is installed,
490 otherwise a C{LazyImportError}.
491 '''
492 g = _xgeographiclib(self.__class__, 1, 49)
493 from geographiclib.geodesic import Geodesic
494 g.Geodesic = Geodesic
495 from geographiclib.geodesicline import GeodesicLine
496 g.GeodesicLine = GeodesicLine
497 from geographiclib.geomath import Math
498 g.Math = Math
499 return g
501 @Property_RO
502 def Math(self):
503 '''Wrap the C{geomath.Math} class, provided the U{geographiclib
504 <https://PyPI.org/project/geographiclib>} package is installed,
505 otherwise C{None}.
506 '''
507 try:
508 g = self.geographiclib
509 M = g.Math
510 if _xversion_info(g) < (2,):
511 if _K_2_0:
512 M = None
513# elif not _K_2_0: # XXX set 2.0?
514# _K_2_0 = True
515 except (AttributeError, ImportError):
516 M = None
517 return M
519_wrapped = _kWrapped() # PYCHOK singleton, .datum, .test/base.py
522class Rhumb8Tuple(_GTuple):
523 '''8-Tuple C{(lat1, lon1, lat2, lon2, azi12, s12, S12, a12)} with lat- C{lat1},
524 C{lat2} and longitudes C{lon1}, C{lon2} of both points, the azimuth of the
525 rhumb line C{azi12}, the distance C{s12}, the area C{S12} under the rhumb
526 line and the angular distance C{a12} between both points.
527 '''
528 _Names_ = (_lat1_, _lon1_, _lat2_, _lon2_, _azi12_, _s12_, _S12_, _a12_)
529 _Units_ = ( Lat, Lon, Lat, Lon, _Azi, _M, _M2, _Deg)
531 def toDirect9Tuple(self, dflt=NAN, **a12_azi1_azi2_m12_M12_M21):
532 '''Convert this L{Rhumb8Tuple} result to a 9-tuple, like I{Karney}'s
533 method C{geographiclib.geodesic.Geodesic._GenDirect}.
535 @kwarg dflt: Default value for missing items (C{any}).
536 @kwarg a12_azi1_azi2_m12_M12_M21: Optional keyword arguments
537 to specify or override L{Inverse10Tuple} items.
539 @return: L{Direct9Tuple}C{(a12, lat2, lon2, azi2, s12,
540 m12, M12, M21, S12)}
541 '''
542 d = dict(azi1=self.azi12, M12=_1_0, m12=self.s12, # PYCHOK attr
543 azi2=self.azi12, M21=_1_0) # PYCHOK attr
544 if a12_azi1_azi2_m12_M12_M21:
545 d.update(a12_azi1_azi2_m12_M12_M21)
546 return self._toTuple(Direct9Tuple, dflt, d)
548 def toInverse10Tuple(self, dflt=NAN, **a12_m12_M12_M21_salp1_calp1_salp2_calp2):
549 '''Convert this L{Rhumb8Tuple} to a 10-tuple, like I{Karney}'s
550 method C{geographiclib.geodesic.Geodesic._GenInverse}.
552 @kwarg dflt: Default value for missing items (C{any}).
553 @kwarg a12_m12_M12_M21_salp1_calp1_salp2_calp2: Optional keyword
554 arguments to specify or override L{Inverse10Tuple} items.
556 @return: L{Inverse10Tuple}C{(a12, s12, salp1, calp1, salp2, calp2,
557 m12, M12, M21, S12)}.
558 '''
559 s, c = sincos2d(self.azi12) # PYCHOK attr
560 d = dict(salp1=s, calp1=c, M12=_1_0, m12=self.s12, # PYCHOK attr
561 salp2=s, calp2=c, M21=_1_0)
562 if a12_m12_M12_M21_salp1_calp1_salp2_calp2:
563 d.update(a12_m12_M12_M21_salp1_calp1_salp2_calp2)
564 return self._toTuple(Inverse10Tuple, dflt, d)
566 def _toTuple(self, nTuple, dflt, updates={}):
567 '''(INTERNAL) Convert this C{Rhumb8Tuple} to an B{C{nTuple}}.
568 '''
569 _g = self.toGDict(**updates).get
570 t = tuple(_g(n, dflt) for n in nTuple._Names_)
571 return nTuple(t, name=self.name)
573 @deprecated_method
574 def _to7Tuple(self):
575 '''DEPRECATED, do not use!'''
576 return _MODS.deprecated.classes.Rhumb7Tuple(self[:-1])
579def _around(x): # in .utily.sincos2d
580 '''I{Coarsen} a scalar by rounding small values to underflow to C{0.0}.
582 @return: Coarsened value (C{float}).
584 @see: I{Karney}'s U{geomath.Math.AngRound<https://SourceForge.net/p/
585 geographiclib/code/ci/release/tree/python/geographiclib/geomath.py>}
586 '''
587 try:
588 return _wrapped.Math.AngRound(x)
589 except AttributeError:
590 if x:
591 y = _1_16th - fabs(x)
592 if y > 0: # fabs(x) < _1_16th
593 x = _copysign(_1_16th - y, x)
594 else:
595 x = _0_0 # -0 to 0
596 return x
599def _atan2d(y, x):
600 '''Return C{atan2(B{y}, B{x})} in C{degrees}.
601 '''
602 try:
603 return _wrapped.Math.atan2d(y, x)
604 except AttributeError:
605 return atan2d(y, x)
608def _cbrt(x):
609 '''Return C{cubic root(B{x})}.
610 '''
611 try:
612 return _wrapped.Math.cbrt(x)
613 except AttributeError:
614 return cbrt(x)
617def _copyBit(x, y):
618 '''Like C{copysign0(B{x}, B{y})}, with C{B{x} > 0}.
619 '''
620 return (-x) if _signBit(y) else x
623def _2cos2x(cx, sx): # in .auxDST, .auxLat, .gxbases
624 '''Return M{2 * cos(2 * x)} from cos(x) and sin(x).
625 '''
626 r = cx - sx
627 if r:
628 r *= (cx + sx) * _2_0
629 return r
632def _diff182(deg0, deg, K_2_0=False):
633 '''Compute C{deg - deg0}, reduced to C{[-180,180]} accurately.
635 @return: 2-Tuple C{(delta_angle, residual)} in C{degrees}.
636 '''
637 try:
638 return _wrapped.Math.AngDiff(deg0, deg)
639 except AttributeError:
640 if K_2_0 or _K_2_0: # geographiclib 2.0
641 _r, _360 = fremainder, _360_0
642 d, t = _sum2(_r(-deg0, _360),
643 _r( deg, _360))
644 d, t = _sum2(_r( d, _360), t)
645 if d in (_0_0, _180_0, _N_180_0):
646 d = _copysign(d, -t if t else (deg - deg0))
647 else:
648 _n = _norm180
649 d, t = _sum2(_n(-deg0), _n(deg))
650 d = _n(d)
651 if t > 0 and d == _180_0:
652 d = _N_180_0
653 d, t = _sum2(d, t)
654 return d, t
657def _fix90(deg): # mimick Math.LatFix
658 '''Replace angle in C{degrees} outside [-90,90] by NAN.
660 @return: Angle C{degrees} or NAN.
661 '''
662 try:
663 return _wrapped.Math.LatFix(deg)
664 except AttributeError:
665 return NAN if fabs(deg) > 90 else deg
668def _isfinite(x): # mimick geomath.Math.isfinite
669 '''Check finiteness of C{x}.
671 @return: C{True} if finite.
672 '''
673 try:
674 return _wrapped.Math.isfinite(x)
675 except AttributeError:
676 return _math_isfinite(x) # and fabs(x) <= _MAX
679def _norm2(x, y): # mimick geomath.Math.norm
680 '''Normalize C{B{x}} and C{B{y}}.
682 @return: 2-Tuple of C{(B{x}, B{y})}, normalized.
683 '''
684 try:
685 return _wrapped.Math.norm(x, y)
686 except AttributeError:
687 return norm2(x, y)
690def _norm180(deg): # mimick geomath.Math.AngNormalize
691 '''Reduce angle in C{degrees} to (-180,180].
693 @return: Reduced angle C{degrees}.
694 '''
695 try:
696 return _wrapped.Math.AngNormalize(deg)
697 except AttributeError:
698 d = fremainder(deg, _360_0)
699 if d in (_180_0, _N_180_0):
700 d = _copysign(_180_0, deg) if _K_2_0 else _180_0
701 return d
704def _polygon(geodesic, points, closed, line, wrap):
705 '''(INTERNAL) Compute the area or perimeter of a polygon,
706 using a L{GeodesicExact}, L{GeodesicSolve} or (if the
707 C{geographiclib} package is installed) a C{Geodesic}
708 or C{geodesicw.Geodesic} instance.
709 '''
710 if not wrap: # capability LONG_UNROLL can't be off
711 notImplemented(None, wrap=wrap, up=3)
713 if _MODS.booleans.isBoolean(points):
714 # recursive call for each boolean clip
716 def _a_p(clip, *args, **unused):
717 return _polygon(geodesic, clip, *args)
719 if not closed: # closed only
720 raise _ValueError(closed=closed, points=_composite_)
722 return points._sum1(_a_p, closed, line, wrap)
724 gP = geodesic.Polygon(line)
725 _A = gP.AddPoint
727 Ps = _MODS.iters.PointsIter(points, loop=1, wrap=wrap) # base=LatLonEllipsoidalBase(0, 0)
728 p1 = p0 = Ps[0]
730 # note, lon deltas are unrolled, by default
731 _A(p1.lat, p1.lon)
732 for p2 in Ps.iterate(closed=closed):
733 if wrap and not Ps.looped:
734 p2 = _unrollon(p1, p2)
735 _A(p2.lat, p2.lon)
736 p1 = p2
737 if closed and line and p1 != p0:
738 _A(p0.lat, p0.lon)
740 # gP.Compute returns (number_of_points, perimeter, signed area)
741 return gP.Compute(False, True)[1 if line else 2]
744def _polynomial(x, cs, i, j): # PYCHOK shared
745 '''(INTERNAL) Like C++ C{GeographicLib.Math.hpp.polyval} but with a
746 different signature and cascaded summation as C{karney._sum2_}.
748 @return: M{sum(cs[k] * x**(j - k - 1) for k in range(i, j)}
749 '''
750 # assert 0 <= i <= j <= len(cs)
751# try:
752# return _wrapped.Math.polyval(j - i - 1, cs, i, x)
753# except AttributeError:
754# s, t = cs[i], _0_0
755# for c in cs[i+1:j]:
756# s, t = _sum2_(s * x, t * x, c)
757# return s # + t
758 s, _ = _sum2_(cs[i], _0_0, x=x, *cs[i+1:j])
759 return s # + t
762def _remainder(x, y):
763 '''Remainder of C{x / y}.
765 @return: Remainder in the range M{[-y / 2, y / 2]}, preserving signed 0.0.
766 '''
767 try:
768 return _wrapped.Math.remainder(x, y)
769 except AttributeError:
770 return fremainder(x, y)
773if _K_2_0:
774 from math import cos as _cos, sin as _sin
776 def _sincos2(rad):
777 return _sin(rad), _cos(rad)
779 _signBit = _MODS.basics.signBit
780else:
781 _sincos2 = _MODS.utily.sincos2 # PYCHOK shared
783 def _signBit(x):
784 '''(INTERNAL) GeographicLib 1.52-.
785 '''
786 return x < 0
789def _sincos2d(deg):
790 '''Return sine and cosine of an angle in C{degrees}.
792 @return: 2-Tuple C{(sin(B{deg}), cos(B{deg}))}.
793 '''
794 try:
795 return _wrapped.Math.sincosd(deg)
796 except AttributeError:
797 return sincos2d(deg)
800def _sincos2de(deg, t):
801 '''Return sine and cosine of a corrected angle in C{degrees}.
803 @return: 2-Tuple C{(sin(B{deg}), cos(B{deg}))}.
804 '''
805 try:
806 return _wrapped.Math.sincosde(deg, t)
807 except AttributeError:
808 return sincos2d(deg, adeg=t)
811def _sum2(u, v): # mimick geomath.Math.sum, actually sum2
812 '''Error-free summation like C{geomath.Math.sum}.
814 @return: 2-Tuple C{(B{u} + B{v}, residual)}.
816 @note: The C{residual} can be the same as B{C{u}} or B{C{v}}.
818 @see: U{Algorithm 3.1<https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}.
819 '''
820 try:
821 return _wrapped.Math.sum(u, v)
822 except AttributeError:
823 s = u + v
824 r = s - v
825 t = s - r
826 # if Algorithm_3_1:
827 # t = (u - t) + (v + r)
828 # elif C_CPP: # Math::sum C/C++
829 # r -= u
830 # t -= v
831 # t += r
832 # t = -t
833 # else:
834 t = (u - r) + (v - t)
835 return s, t
838def _sum2_(s, t, *vs, **x):
839 '''Accumulate any B{C{vs}} into a previous C{_sum2(s, t)}.
841 @kwarg x: Optional polynomial C{B{x}=1} (C{scalar}).
843 @return: 2-Tuple C{(B{s} + B{t} + sum(B{vs}), residual)}.
845 @see: I{Karney's} C++ U{Accumulator<https://GeographicLib.SourceForge.io/
846 html/Accumulator_8hpp_source.html>} comments for more details and
847 function C{_sum2} above.
849 @note: NOT "error-free", see C{pygeodesy.test/testKarney.py}.
850 '''
851 x = _xkwds_get(x, x=0)
853 _s2, _u0 = _sum2, unsigned0
854 for v in vs:
855 if x:
856 s *= x
857 t *= x
858 if v:
859 t, u = _s2(t, v) # start at the least-
860 if s:
861 s, t = _s2(s, t) # significant end
862 if s:
863 t += u # accumulate u into t
864# elif t: # s == 0 implies t == 0
865# raise _AssertionError(t=t, txt=_not_(_0_))
866 else:
867 s = _u0(u) # result is u, t = 0
868 else:
869 s, t = _u0(t), u
870 return s, t
873def _tand(x):
874 '''Return C{tan(B{x})} in C{degrees}.
875 '''
876 try:
877 return _wrapped.Math.tand(x)
878 except AttributeError:
879 return tand(x)
882def _unroll2(lon1, lon2, wrap=False): # see .ellipsoidalBaseDI._intersects2
883 '''Unroll B{C{lon2 - lon1}} like C{geodesic.Geodesic.Inverse}.
885 @return: 2-Tuple C{(B{lon2} - B{lon1}, B{lon2})} with B{C{lon2}}
886 unrolled if B{C{wrap}} is C{True}, normalized otherwise.
887 '''
888 if wrap:
889 d, t = _diff182(lon1, lon2)
890 lon2, _ = _sum2_(d, t, lon1) # (lon1 + d) + t
891 else:
892 lon2 = _norm180(lon2)
893 return (lon2 - lon1), lon2
896def _unsigned2(x):
897 '''(INTERNAL) Unsign B{C{x}}.
898 '''
899 return (neg(x), True) if _signBit(x) else (x, False)
902__all__ += _ALL_DOCS(_CapsBase)
904# **) MIT License
905#
906# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
907#
908# Permission is hereby granted, free of charge, to any person obtaining a
909# copy of this software and associated documentation files (the "Software"),
910# to deal in the Software without restriction, including without limitation
911# the rights to use, copy, modify, merge, publish, distribute, sublicense,
912# and/or sell copies of the Software, and to permit persons to whom the
913# Software is furnished to do so, subject to the following conditions:
914#
915# The above copyright notice and this permission notice shall be included
916# in all copies or substantial portions of the Software.
917#
918# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
919# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
920# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
921# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
922# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
923# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
924# OTHER DEALINGS IN THE SOFTWARE.