Coverage for pygeodesy/karney.py: 94%
287 statements
« prev ^ index » next coverage.py v7.2.2, created at 2024-06-01 11:43 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2024-06-01 11:43 -0400
2# -*- coding: utf-8 -*-
4u'''Wrapper around several C{geomath.Math} functions from I{Karney}'s Python package U{geographiclib
5<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.
9All methods of the I{wrapped} L{Geodesic<geodesicw.Geodesic>} and L{GeodesicLine<geodesicw.GeodesicLine>}
10classes return a L{GDict} instance offering access to the C{dict} items either by C{key} or by
11C{attribute} name.
13With env variable C{PYGEODESY_GEOGRAPHICLIB} left undefined or set to C{"2"}, modules L{geodesicx},
14L{geodesicw} and this module will use U{GeographicLib 2.0<https://GeographicLib.SourceForge.io/C++/doc/>}
15and newer transcoding, otherwise C{1.52} or older.
17Karney-based functionality
18==========================
201. The following classes and functions in C{pygeodesy}
22 - L{AlbersEqualArea}, L{AlbersEqualArea2}, L{AlbersEqualArea4},
23 L{AlbersEqualAreaCylindrical}, L{AlbersEqualAreaNorth}, L{AlbersEqualAreaSouth} --
24 U{AlbersEqualArea<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1AlbersEqualArea.html>}
26 - L{AuxAngle}, L{AuxDST}, L{AuxDLat}, L{AuxLat} -- U{AuxAngle
27 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1AuxAngle.html>},
28 U{DST<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1DST.html>},
29 U{DAuxLatitude<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1DAuxLatitude.html>},
30 U{AuxLatitude<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1AuxLatitude.html>} in I{GeographicLib 2.2+}
32 - L{CassiniSoldner} -- U{CassiniSoldner<https://GeographicLib.SourceForge.io/C++/doc/
33 classGeographicLib_1_1CassiniSoldner.html>}
35 - L{EcefKarney} -- U{Geocentric<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Geocentric.html>}
37 - L{Elliptic} -- U{EllipticFunction<https://GeographicLib.SourceForge.io/C++/doc/
38 classGeographicLib_1_1EllipticFunction.html>}
40 - L{EquidistantExact}, L{EquidistantGeodSolve}, L{EquidistantKarney} -- U{AzimuthalEquidistant
41 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1AzimuthalEquidistant.html>}
43 - L{Etm}, L{ExactTransverseMercator} -- U{TransverseMercatorExact
44 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1TransverseMercatorExact.html>}
46 - L{Geodesic}, L{GeodesicLine} -- I{wrapped} U{geodesic.Geodesic<https://PyPI.org/project/geographiclib>},
47 I{wrapped} U{geodesicline.GeodesicLine<https://PyPI.org/project/geographiclib>}
49 - L{GeodesicAreaExact}, L{PolygonArea} -- U{PolygonArea<https://GeographicLib.SourceForge.io/C++/doc/
50 classGeographicLib_1_1PolygonAreaT.html>}
52 - L{GeodesicExact}, L{GeodesicLineExact} -- U{GeodesicExact<https://GeographicLib.SourceForge.io/C++/doc/
53 classGeographicLib_1_1GeodesicExact.html>}, U{GeodesicLineExact<https://GeographicLib.SourceForge.io/C++/doc/
54 classGeographicLib_1_1GeodesicLineExact.html>}
56 - L{GeoidKarney} -- U{Geoid<https://GeographicLib.SourceForge.io/C++/doc/geoid.html>}
58 - L{Georef} -- U{Georef<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Georef.html>}
60 - L{GnomonicExact}, L{GnomonicGeodSolve}, L{GnomonicKarney} -- U{Gnomonic
61 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Gnomonic.html>}
63 - L{JacobiConformal} -- U{JacobiConformal
64 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1JacobiConformal.html#details>}
66 - L{KTransverseMercator} - U{TransverseMercator
67 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1TransverseMercator.html>}
69 - L{LocalCartesian}, L{Ltp} -- U{LocalCartesian<https://GeographicLib.SourceForge.io/C++/doc/
70 classGeographicLib_1_1LocalCartesian.html>}
72 - L{Osgr} -- U{OSGB<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1OSGB.html>}
74 - L{rhumb.aux_}, L{RhumbAux}, L{RhumbLineAux} -- U{Rhumb
75 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Rhumb.html>} and U{RhumbLine
76 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1RhumbLine.html>} from I{GeographicLib 2.2+}
78 - L{rhumb.ekx}, L{Rhumb}, L{RhumbLine} -- U{Rhumb
79 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Rhumb.html>},
80 U{RhumbLine<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1RhumbLine.html>},
81 U{TransverseMercator<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1TransverseMercator.html>}
82 from I{GeographicLib 2.0}
84 - L{Ups} -- U{PolarStereographic<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1PolarStereographic.html>}
86 - L{Utm} -- U{TransverseMercator<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1TransverseMercator.html>}
88 - L{UtmUps}, L{Epsg} -- U{UTMUPS<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1UTMUPS.html>}
90 - L{atan1d}, L{atan2d}, L{sincos2}, L{sincos2d}, L{tand} -- U{geomath.Math
91 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Math.html>}
93are I{transcoded} from C++ classes in I{Karney}'s U{GeographicLib<https://GeographicLib.SourceForge.io/C++/doc/annotated.html>}.
952. These C{pygeodesy} modules and classes
97 - L{ellipsoidalGeodSolve}, L{ellipsoidalKarney}, L{geodsolve}, L{karney}, L{rhumb.solve}
98 - L{EquidistantKarney}, L{FrechetKarney}, L{GeodesicSolve}, L{GeodesicLineSolve}, L{GnomonicGeodSolve},
99 L{GnomonicKarney}, L{HeightIDWkarney}
101are or use I{wrappers} around I{Karney}'s Python U{geographiclib<https://PyPI.org/project/geographiclib>}
102C{geodesic}, C++ utility U{GeodSolve<https://GeographicLib.SourceForge.io/C++/doc/GeodSolve.1.html>} or
103C++ utility U{RhumbSolve<https://GeographicLib.SourceForge.io/C++/doc/RhumbSolve.1.html>}.
1053. All C{pygeodesy} functions and methods to compute I{ellipsoidal} intersections, nearest points and trilaterations
107 - L{ellipsoidalExact.intersection3}, L{ellipsoidalExact.intersections2}, L{ellipsoidalExact.nearestOn},
108 L{ellipsoidalExact.LatLon.intersection3}, L{ellipsoidalExact.LatLon.intersections2},
109 L{ellipsoidalExact.LatLon.nearestOn}, L{ellipsoidalExact.LatLon.trilaterate5}
111 - L{ellipsoidalKarney.intersection3}, L{ellipsoidalKarney.intersections2}, L{ellipsoidalKarney.nearestOn},
112 L{ellipsoidalKarney.LatLon.intersection3}, L{ellipsoidalKarney.LatLon.intersections2},
113 L{ellipsoidalKarney.LatLon.nearestOn}, L{ellipsoidalKarney.LatLon.trilaterate5}
115 - L{ellipsoidalVincenty.intersection3}, L{ellipsoidalVincenty.intersections2}, L{ellipsoidalVincenty.nearestOn},
116 L{ellipsoidalVincenty.LatLon.intersection3}, L{ellipsoidalVincenty.LatLon.intersections2},
117 L{ellipsoidalVincenty.LatLon.nearestOn}, L{ellipsoidalVincenty.LatLon.trilaterate5}
119 - L{RhumbLineAux.Intersection} and L{RhumbLine.Intersection}
121are implementations of I{Karney}'s iterative solution posted under U{The B{ellipsoidal} case
122<https://GIS.StackExchange.com/questions/48937/calculating-intersection-of-two-circles>} and in paper U{Geodesics
123on an ellipsoid of revolution<https://ArXiv.org/pdf/1102.1215.pdf>} (pp 20-21, section B{14. MARITIME BOUNDARIES}).
1254. The C{pygeodesy} methods to compute I{ellipsoidal} intersections and nearest points
127 - L{RhumbLineAux.Intersecant2}, L{RhumbLineAux.PlumbTo}, L{RhumbLine.Intersecant2} and L{RhumbLine.PlumbTo}
129are I{transcoded} of I{Karney}'s iterative C++ function U{rhumb-intercept
130<https://SourceForge.net/p/geographiclib/discussion/1026620/thread/2ddc295e/>}.
1325. Spherical functions
134 - L{pygeodesy.excessKarney_}, L{sphericalTrigonometry.areaOf}
136in C{pygeodesy} are based on I{Karney}'s post U{Area of a spherical polygon
137<https://MathOverflow.net/questions/97711/the-area-of-spherical-polygons>}, 3rd Answer.
138'''
139# make sure int/int division yields float quotient, see .basics
140from __future__ import division as _; del _ # PYCHOK semicolon
142from pygeodesy.basics import _copysign, int1s, isint, itemsorted, neg, unsigned0, \
143 _xgeographiclib, _zip, _version_info
144from pygeodesy.constants import NAN, _isfinite as _math_isfinite, _0_0, \
145 _1_16th, _1_0, _2_0, _180_0, _N_180_0, _360_0
146from pygeodesy.errors import GeodesicError, _ValueError, _xkwds, _xkwds_get1
147from pygeodesy.fmath import cbrt, fremainder, norm2
148# from pygeodesy.internals import _version_info # from .basics
149from pygeodesy.interns import _2_, _a12_, _area_, _azi2_, _azi12_, _composite_, \
150 _lat1_, _lat2_, _lon1_, _lon2_, _m12_, _M12_, \
151 _M21_, _number_, _s12_, _S12_, _UNDER_, \
152 _BAR_, NN # PYCHOK used!
153from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS, _getenv
154from pygeodesy.named import ADict, _NamedBase, _NamedTuple, notImplemented, _Pass
155from pygeodesy.props import deprecated_method, Property_RO
156from pygeodesy.units import Bearing as _Azi, Degrees as _Deg, Lat, Lon, \
157 Meter as _M, Meter2 as _M2, Number_
158from pygeodesy.utily import atan2d, sincos2d, tand, _unrollon, fabs
160# from math import fabs # from .utily
162__all__ = _ALL_LAZY.karney
163__version__ = '24.05.31'
165_K_2_0 = _getenv('PYGEODESY_GEOGRAPHICLIB', _2_) == _2_
166_perimeter_ = 'perimeter'
169class _GTuple(_NamedTuple): # in .testNamedTuples
170 '''(INTERNAL) Helper.
171 '''
172 def toGDict(self, **updates): # NO name=NN
173 '''Convert this C{*Tuple} to a L{GDict}.
175 @kwarg updates: Optional items to apply (C{name=value} pairs)
176 '''
177 r = GDict(_zip(self._Names_, self)) # strict=True
178 if updates:
179 r.update(updates)
180 if self._iteration is not None:
181 r._iteration = self._iteration
182 return r
185class _Lat(Lat):
186 '''(INTERNAL) Latitude B{C{lat}}.
187 '''
188 def __init__(self, *lat, **Error_name):
189 kwds = _xkwds(Error_name, clip=0, Error=GeodesicError)
190 Lat.__new__(_Lat, *lat, **kwds)
193class _Lon(Lon):
194 '''(INTERNAL) Longitude B{C{lon}}.
195 '''
196 def __init__(self, *lon, **Error_name):
197 kwds = _xkwds(Error_name, clip=0, Error=GeodesicError)
198 Lon.__new__(_Lon, *lon, **kwds)
201class Area3Tuple(_NamedTuple): # in .geodesicx.gxarea
202 '''3-Tuple C{(number, perimeter, area)} with the C{number}
203 of points of the polygon or polyline, the C{perimeter} in
204 C{meter} and the C{area} in C{meter} I{squared}.
205 '''
206 _Names_ = (_number_, _perimeter_, _area_)
207 _Units_ = ( Number_, _M, _M2)
210class Caps(object): # PYCHOK
211 '''(INTERNAL) Overriden by C{Caps} below.
212 '''
213 EMPTY = 0 # formerly aka NONE
214 _CAP_1 = 1 << 0 # for goedesicw only
215 _CAP_1p = 1 << 1 # for goedesicw only
216# _CAP_2 = 1 << 2
217 _CAP_3 = 1 << 3 # for goedesicw only
218# _CAP_4 = 1 << 4
219# _CAP_ALL = 0x1F
220# _CAP_MASK = _CAP_ALL
221 LATITUDE = 1 << 7 # compute latitude C{lat2}
222 LONGITUDE = 1 << 8 # compute longitude C{lon2} _CAP_3
223 AZIMUTH = 1 << 9 # azimuths C{azi1} and C{azi2}
224 DISTANCE = 1 << 10 # compute distance C{s12} _CAP_1
225 DISTANCE_IN = 1 << 11 # allow distance C{s12} in Direct _CAP_1 | _CAP_1p
226 REDUCEDLENGTH = 1 << 12 # compute reduced length C{m12} _CAP_1 | _CAP_2
227 GEODESICSCALE = 1 << 13 # compute geodesic scales C{M12} and C{M21} _CAP_1 | _CAP_2
228 AREA = 1 << 14 # compute area C{S12} _CAP_4
230 STANDARD = AZIMUTH | DISTANCE | DISTANCE_IN | LATITUDE | LONGITUDE
231 ALL = 0x7F80 # without LONG_UNROLL, LINE_OFF, REVERSE2 and _DEBUG_*
233 _DIRECT3 = AZIMUTH | LATITUDE | LONGITUDE | _CAP_3 # for goedesicw only
234 _INVERSE3 = AZIMUTH | DISTANCE | _CAP_1 # for goedesicw only
235 _STD = STANDARD | _CAP_3 | _CAP_1 # for goedesicw only
236 _STD_LINE = _STD | _CAP_1p # for goedesicw only
238 LINE_OFF = 1 << 15 # Line without updates from parent geodesic or rhumb
239 LONG_UNROLL = 1 << 16 # unroll C{lon2} in .Direct and .Position
240 REVERSE2 = 1 << 17 # reverse C{azi2}
242 LATITUDE_LONGITUDE = LATITUDE | LONGITUDE
243 LATITUDE_LONGITUDE_AREA = LATITUDE | LONGITUDE | AREA
245 AZIMUTH_DISTANCE = AZIMUTH | DISTANCE
246 AZIMUTH_DISTANCE_AREA = AZIMUTH | DISTANCE | AREA
248 _ANGLE_ONLY = 1 << 18 # angular distance C{a12} only
249 _SALPs_CALPs = 1 << 19 # (INTERNAL) GeodesicExact._GenInverse
251 _DEBUG_AREA = 1 << 20 # (INTERNAL) include Line details
252 _DEBUG_DIRECT = 1 << 21 # (INTERNAL) include Direct details
253 _DEBUG_INVERSE = 1 << 22 # (INTERNAL) include Inverse details
254 _DEBUG_LINE = 1 << 23 # (INTERNAL) include Line details
255 _DEBUG_ALL = _DEBUG_AREA | _DEBUG_DIRECT | _DEBUG_INVERSE | \
256 _DEBUG_LINE | _ANGLE_ONLY | _SALPs_CALPs
258 _OUT_ALL = ALL
259 _OUT_MASK = ALL | LONG_UNROLL | REVERSE2 | _DEBUG_ALL
261 _AZIMUTH_LATITUDE_LONGITUDE = AZIMUTH | LATITUDE | LONGITUDE
262 _DEBUG_DIRECT_LINE = _DEBUG_DIRECT | _DEBUG_LINE
263# _DISTANCE_IN_OUT = DISTANCE_IN & _OUT_MASK # == DISTANCE_IN in .gx, .gxline
264 _LINE = AZIMUTH | LATITUDE | LONG_UNROLL
265 _REDUCEDLENGTH_GEODESICSCALE = REDUCEDLENGTH | GEODESICSCALE
266# _REDUCEDLENGTH_GEODESICSCALE_DISTANCE = REDUCEDLENGTH | GEODESICSCALE | DISTANCE
268 def toStr(self, Csk, sep=_BAR_):
269 '''Return a C{Caps} or C{outmask} as C{str} or tuple of C{str}s.
270 '''
271 s = []
272 for c, C in itemsorted(self.__class__.__dict__):
273 if isint(C) and (Csk & C) and int1s(C) == 1 \
274 and (C in (Caps.REVERSE2, Caps._SALPs_CALPs)
275 or c.replace(_UNDER_, NN).isupper()):
276 s.append(c)
277 return sep.join(s) if sep else tuple(s)
279Caps = Caps() # PYCHOK singleton
280'''I{Enum}-style masks to be bit-C{or}'ed to specify geodesic or
281rhumb capabilities (C{caps}) and expected results (C{outmask}).
283C{AREA} - compute area C{S12},
285C{AZIMUTH} - include azimuths C{azi1} and C{azi2},
287C{DISTANCE} - compute distance C{s12},
289C{DISTANCE_IN} - allow distance C{s12} in C{.Direct},
291C{EMPTY} - nothing, formerly aka C{NONE},
293C{GEODESICSCALE} - compute geodesic scales C{M12} and C{M21},
295C{LATITUDE} - compute latitude C{lat2},
297C{LINE_OFF} - Line without updates from parent geodesic or rhumb.
299C{LONGITUDE} - compute longitude C{lon2},
301C{LONG_UNROLL} - unroll C{lon2} in C{.Direct},
303C{REDUCEDLENGTH} - compute reduced length C{m12},
305C{REVERSE2} - reverse C{azi2},
307and C{ALL} - all of the above.
309C{STANDARD} = C{AZIMUTH | DISTANCE | DISTANCE_IN | LATITUDE | LONGITUDE}'''
312class _CapsBase(_NamedBase): # in .auxilats, .geodesicx.gxbases
313 '''(INTERNAL) Base class for C{[_]Geodesic*Exact}.
314 '''
315 ALL = Caps.ALL
316 AREA = Caps.AREA
317 AZIMUTH = Caps.AZIMUTH
318 DISTANCE = Caps.DISTANCE
319 DISTANCE_IN = Caps.DISTANCE_IN
320 EMPTY = Caps.EMPTY # aka NONE
321 GEODESICSCALE = Caps.GEODESICSCALE
322 LATITUDE = Caps.LATITUDE
323 LINE_OFF = Caps.LINE_OFF
324 LONGITUDE = Caps.LONGITUDE
325 LONG_UNROLL = Caps.LONG_UNROLL
326 REDUCEDLENGTH = Caps.REDUCEDLENGTH
327 STANDARD = Caps.STANDARD
329 _caps = 0 # None
330 _debug = 0 # or Caps._DEBUG_...
332 @Property_RO
333 def caps(self):
334 '''Get the capabilities (bit-or'ed C{Caps}).
335 '''
336 return self._caps
338 def caps_(self, caps):
339 '''Check the available capabilities.
341 @arg caps: Bit-or'ed combination of L{Caps} values
342 for all capabilities to be checked.
344 @return: C{True} if I{all} B{C{caps}} are available,
345 C{False} otherwise (C{bool}).
346 '''
347 caps &= Caps._OUT_ALL
348 return (self.caps & caps) == caps
350 @property
351 def debug(self):
352 '''Get the C{debug} option (C{bool}).
353 '''
354 return bool(self._debug)
356 @debug.setter # PYCHOK setter!
357 def debug(self, debug):
358 '''Set the C{debug} option (C{bool}) to include
359 more details in L{GDict} results.
360 '''
361 self._debug = Caps._DEBUG_ALL if debug else 0
363 def _iter2tion(self, r, iter=None, **unused):
364 '''(INTERNAL) Copy C{C{s}.iter} into C{B{r}._iteration}.
365 '''
366 if iter is not None:
367 self._iteration = r._iteration = iter
368 return r
371class 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)
381class GDict(ADict): # XXX _NamedDict
382 '''A C{dict} with both C{key} I{and} C{attribute} access to the C{dict} items.
384 Results of all C{geodesic} and C{rhumb} methods (with capitalized named) are
385 returned as L{GDict} instances, see for example L{GeodesicExact} and L{RhumbAux}.
386 '''
387 def toDirect9Tuple(self, dflt=NAN):
388 '''Convert this L{GDict} result to a 9-tuple, like I{Karney}'s method
389 C{geographiclib.geodesic.Geodesic._GenDirect}.
391 @kwarg dflt: Default value for missing items (C{any}).
393 @return: L{Direct9Tuple}C{(a12, lat2, lon2, azi2,
394 s12, m12, M12, M21, S12)}
395 '''
396 return self._toTuple(Direct9Tuple, dflt)
398 def toGeodSolve12Tuple(self, dflt=NAN): # PYCHOK 12 args
399 '''Convert this L{GDict} result to a 12-Tuple, compatible with I{Karney}'s
400 U{GeodSolve<https://GeographicLib.SourceForge.io/C++/doc/GeodSolve.1.html>}
401 result.
403 @kwarg dflt: Default value for missing items (C{any}).
405 @return: L{GeodSolve12Tuple}C{(lat1, lon1, azi1, lat2, lon2, azi2,
406 s12, a12, m12, M12, M21, S12)}.
407 '''
408 return self._toTuple(_MODS.geodsolve.GeodSolve12Tuple, dflt)
410 def toInverse10Tuple(self, dflt=NAN):
411 '''Convert this L{GDict} result to a 10-tuple, like I{Karney}'s
412 method C{geographiclib.geodesic.Geodesic._GenInverse}.
414 @kwarg dflt: Default value for missing items (C{any}).
416 @return: L{Inverse10Tuple}C{(a12, s12, salp1, calp1,
417 salp2, calp2, m12, M12, M21, S12)}.
418 '''
419 return self._toTuple(Inverse10Tuple, dflt)
421 @deprecated_method
422 def toRhumb7Tuple(self, dflt=NAN): # PYCHOK no cover
423 '''DEPRECATED on 23.12.07, use method C{toRhumb8Tuple}.
425 @return: A I{DEPRECATED} L{Rhumb7Tuple}.
426 '''
427 return self._toTuple(_MODS.deprecated.classes.Rhumb7Tuple, dflt)
429 def toRhumb8Tuple(self, dflt=NAN):
430 '''Convert this L{GDict} result to a 8-tuple.
432 @kwarg dflt: Default value for missing items (C{any}).
434 @return: L{Rhumb8Tuple}C{(lat1, lon1, lat2, lon2,
435 azi12, s12, S12, a12)}.
436 '''
437 return self._toTuple(Rhumb8Tuple, dflt)
439 def toRhumbSolve7Tuple(self, dflt=NAN):
440 '''Convert this L{GDict} result to a 8-tuple.
442 @kwarg dflt: Default value for missing items (C{any}).
444 @return: L{RhumbSolve7Tuple}C{(lat1, lon1, lat2, lon2,
445 azi12, s12, S12)}.
446 '''
447 return self._toTuple(_MODS.rhumb.solve.RhumbSolve7Tuple, dflt)
449 def _toTuple(self, nTuple, dflt):
450 '''(INTERNAL) Convert this C{GDict} to an B{C{nTuple}}.
451 '''
452 _g = getattr
453 t = tuple(_g(self, n, dflt) for n in nTuple._Names_)
454 return nTuple(t, iteration=self._iteration)
457class Inverse10Tuple(_GTuple):
458 '''10-Tuple C{(a12, s12, salp1, calp1, salp2, calp2, m12, M12, M21, S12)} with arc length
459 C{a12} in C{degrees}, distance C{s12} and reduced length C{m12} in C{meter}, area
460 C{S12} in C{meter} I{squared} and the sines C{salp1}, C{salp2} and cosines C{calp1},
461 C{calp2} of the initial C{1} and final C{2} (forward) azimuths.
462 '''
463 _Names_ = (_a12_, _s12_, 'salp1', 'calp1', 'salp2', 'calp2', _m12_, _M12_, _M21_, _S12_)
464 _Units_ = (_Azi, _M, _Pass, _Pass, _Pass, _Pass, _Pass, _Pass, _Pass, _M2)
466 def toGDict(self, **updates):
467 '''Convert this C{Inverse10Tuple} to a L{GDict}.
469 @kwarg updates: Optional items to apply (C{nam=value} pairs)
470 '''
471 return _GTuple.toGDict(self, azi1=atan2d(self.salp1, self.calp1), # PYCHOK namedTuple
472 azi2=atan2d(self.salp2, self.calp2), # PYCHOK namedTuple
473 **updates) # PYCHOK indent
476class _kWrapped(object): # in .geodesicw
477 ''''(INTERNAL) Wrapper for some of I{Karney}'s U{geographiclib
478 <https://PyPI.org/project/geographiclib>} classes.
479 '''
481 @Property_RO
482 def geographiclib(self):
483 '''Lazily import C{geographiclib}, provided the U{geographiclib
484 <https://PyPI.org/project/geographiclib>} package is installed,
485 otherwise raise a C{LazyImportError}.
486 '''
487 g = _xgeographiclib(self.__class__, 1, 49)
488 from geographiclib.geodesic import Geodesic
489 g.Geodesic = Geodesic
490 from geographiclib.geodesicline import GeodesicLine
491 g.GeodesicLine = GeodesicLine
492 from geographiclib.geomath import Math
493 g.Math = Math
494 return g
496 @Property_RO
497 def Math(self):
498 '''Wrap the C{geomath.Math} class, provided the U{geographiclib
499 <https://PyPI.org/project/geographiclib>} package is installed,
500 otherwise C{None}.
501 '''
502 try:
503 g = self.geographiclib
504 M = g.Math
505 if _version_info(g) < (2,):
506 if _K_2_0:
507 M = None
508# elif not _K_2_0: # XXX set 2.0?
509# _K_2_0 = True
510 except (AttributeError, ImportError):
511 M = None
512 return M
514_wrapped = _kWrapped() # PYCHOK singleton, .datum, .test/base.py
517class Rhumb8Tuple(_GTuple):
518 '''8-Tuple C{(lat1, lon1, lat2, lon2, azi12, s12, S12, a12)} with lat- C{lat1},
519 C{lat2} and longitudes C{lon1}, C{lon2} of both points, the azimuth of the
520 rhumb line C{azi12}, the distance C{s12}, the area C{S12} under the rhumb
521 line and the angular distance C{a12} between both points.
522 '''
523 _Names_ = (_lat1_, _lon1_, _lat2_, _lon2_, _azi12_, _s12_, _S12_, _a12_)
524 _Units_ = ( Lat, Lon, Lat, Lon, _Azi, _M, _M2, _Deg)
526 def toDirect9Tuple(self, dflt=NAN, **a12_azi1_azi2_m12_M12_M21):
527 '''Convert this L{Rhumb8Tuple} result to a 9-tuple, like I{Karney}'s
528 method C{geographiclib.geodesic.Geodesic._GenDirect}.
530 @kwarg dflt: Default value for missing items (C{any}).
531 @kwarg a12_azi1_azi2_m12_M12_M21: Optional keyword arguments
532 to specify or override L{Inverse10Tuple} items.
534 @return: L{Direct9Tuple}C{(a12, lat2, lon2, azi2, s12,
535 m12, M12, M21, S12)}
536 '''
537 d = dict(azi1=self.azi12, M12=_1_0, m12=self.s12, # PYCHOK attr
538 azi2=self.azi12, M21=_1_0) # PYCHOK attr
539 if a12_azi1_azi2_m12_M12_M21:
540 d.update(a12_azi1_azi2_m12_M12_M21)
541 return self._toTuple(Direct9Tuple, dflt, d)
543 def toInverse10Tuple(self, dflt=NAN, **a12_m12_M12_M21_salp1_calp1_salp2_calp2):
544 '''Convert this L{Rhumb8Tuple} to a 10-tuple, like I{Karney}'s
545 method C{geographiclib.geodesic.Geodesic._GenInverse}.
547 @kwarg dflt: Default value for missing items (C{any}).
548 @kwarg a12_m12_M12_M21_salp1_calp1_salp2_calp2: Optional keyword
549 arguments to specify or override L{Inverse10Tuple} items.
551 @return: L{Inverse10Tuple}C{(a12, s12, salp1, calp1, salp2, calp2,
552 m12, M12, M21, S12)}.
553 '''
554 s, c = sincos2d(self.azi12) # PYCHOK attr
555 d = dict(salp1=s, calp1=c, M12=_1_0, m12=self.s12, # PYCHOK attr
556 salp2=s, calp2=c, M21=_1_0)
557 if a12_m12_M12_M21_salp1_calp1_salp2_calp2:
558 d.update(a12_m12_M12_M21_salp1_calp1_salp2_calp2)
559 return self._toTuple(Inverse10Tuple, dflt, d)
561 def _toTuple(self, nTuple, dflt, updates={}):
562 '''(INTERNAL) Convert this C{Rhumb8Tuple} to an B{C{nTuple}}.
563 '''
564 _g = self.toGDict(**updates).get
565 t = tuple(_g(n, dflt) for n in nTuple._Names_)
566 return nTuple(t, name=self.name)
568 @deprecated_method
569 def _to7Tuple(self):
570 '''DEPRECATED, do not use!'''
571 return _MODS.deprecated.classes.Rhumb7Tuple(self[:-1])
574def _around(x): # in .utily.sincos2d
575 '''I{Coarsen} a scalar by rounding small values to underflow to C{0.0}.
577 @return: Coarsened value (C{float}).
579 @see: I{Karney}'s U{geomath.Math.AngRound<https://SourceForge.net/p/
580 geographiclib/code/ci/release/tree/python/geographiclib/geomath.py>}
581 '''
582 try:
583 return _wrapped.Math.AngRound(x)
584 except AttributeError:
585 if x:
586 y = _1_16th - fabs(x)
587 if y > 0: # fabs(x) < _1_16th
588 x = _copysign(_1_16th - y, x)
589 else:
590 x = _0_0 # -0 to 0
591 return x
594def _atan2d(y, x):
595 '''Return C{atan2(B{y}, B{x})} in C{degrees}.
596 '''
597 try:
598 return _wrapped.Math.atan2d(y, x)
599 except AttributeError:
600 return atan2d(y, x)
603def _cbrt(x):
604 '''Return C{cubic root(B{x})}.
605 '''
606 try:
607 return _wrapped.Math.cbrt(x)
608 except AttributeError:
609 return cbrt(x)
612def _copyBit(x, y):
613 '''Like C{copysign0(B{x}, B{y})}, with C{B{x} > 0}.
614 '''
615 return (-x) if _signBit(y) else x
618def _2cos2x(cx, sx): # in .auxDST, .auxLat, .gxbases
619 '''Return M{2 * cos(2 * x)} from cos(x) and sin(x).
620 '''
621 r = cx - sx
622 if r:
623 r *= (cx + sx) * _2_0
624 return r
627def _diff182(deg0, deg, K_2_0=False):
628 '''Compute C{deg - deg0}, reduced to C{[-180,180]} accurately.
630 @return: 2-Tuple C{(delta_angle, residual)} in C{degrees}.
631 '''
632 try:
633 return _wrapped.Math.AngDiff(deg0, deg)
634 except AttributeError:
635 if K_2_0 or _K_2_0: # geographiclib 2.0
636 _r, _360 = fremainder, _360_0
637 d, t = _sum2(_r(-deg0, _360),
638 _r( deg, _360))
639 d, t = _sum2(_r( d, _360), t)
640 if d in (_0_0, _180_0, _N_180_0):
641 d = _copysign(d, -t if t else (deg - deg0))
642 else:
643 _n = _norm180
644 d, t = _sum2(_n(-deg0), _n(deg))
645 d = _n(d)
646 if t > 0 and d == _180_0:
647 d = _N_180_0
648 d, t = _sum2(d, t)
649 return d, t
652def _fix90(deg): # mimick Math.LatFix
653 '''Replace angle in C{degrees} outside [-90,90] by NAN.
655 @return: Angle C{degrees} or NAN.
656 '''
657 try:
658 return _wrapped.Math.LatFix(deg)
659 except AttributeError:
660 return NAN if fabs(deg) > 90 else deg
663def _isfinite(x): # mimick geomath.Math.isfinite
664 '''Check finiteness of C{x}.
666 @return: C{True} if finite.
667 '''
668 try:
669 return _wrapped.Math.isfinite(x)
670 except AttributeError:
671 return _math_isfinite(x) # and fabs(x) <= _MAX
674def _norm2(x, y): # mimick geomath.Math.norm
675 '''Normalize C{B{x}} and C{B{y}}.
677 @return: 2-Tuple of C{(B{x}, B{y})}, normalized.
678 '''
679 try:
680 return _wrapped.Math.norm(x, y)
681 except AttributeError:
682 return norm2(x, y)
685def _norm180(deg): # mimick geomath.Math.AngNormalize
686 '''Reduce angle in C{degrees} to (-180,180].
688 @return: Reduced angle C{degrees}.
689 '''
690 try:
691 return _wrapped.Math.AngNormalize(deg)
692 except AttributeError:
693 d = fremainder(deg, _360_0)
694 if d in (_180_0, _N_180_0):
695 d = _copysign(_180_0, deg) if _K_2_0 else _180_0
696 return d
699def _polygon(geodesic, points, closed, line, wrap):
700 '''(INTERNAL) Compute the area or perimeter of a polygon,
701 using a L{GeodesicExact}, L{GeodesicSolve} or (if the
702 C{geographiclib} package is installed) a C{Geodesic}
703 or C{geodesicw.Geodesic} instance.
704 '''
705 if not wrap: # capability LONG_UNROLL can't be off
706 notImplemented(None, wrap=wrap, up=3)
708 if _MODS.booleans.isBoolean(points):
709 # recursive call for each boolean clip
711 def _a_p(clip, *args, **unused):
712 return _polygon(geodesic, clip, *args)
714 if not closed: # closed only
715 raise _ValueError(closed=closed, points=_composite_)
717 return points._sum1(_a_p, closed, line, wrap)
719 gP = geodesic.Polygon(line)
720 _A = gP.AddPoint
722 Ps = _MODS.iters.PointsIter(points, loop=1, wrap=wrap) # base=LatLonEllipsoidalBase(0, 0)
723 p1 = p0 = Ps[0]
725 # note, lon deltas are unrolled, by default
726 _A(p1.lat, p1.lon)
727 for p2 in Ps.iterate(closed=closed):
728 if wrap and not Ps.looped:
729 p2 = _unrollon(p1, p2)
730 _A(p2.lat, p2.lon)
731 p1 = p2
732 if closed and line and p1 != p0:
733 _A(p0.lat, p0.lon)
735 # gP.Compute returns (number_of_points, perimeter, signed area)
736 return gP.Compute(False, True)[1 if line else 2]
739def _polynomial(x, cs, i, j): # PYCHOK shared
740 '''(INTERNAL) Like C++ C{GeographicLib.Math.hpp.polyval} but with a
741 different signature and cascaded summation as C{karney._sum2_}.
743 @return: M{sum(cs[k] * x**(j - k - 1) for k in range(i, j)}
744 '''
745 # assert 0 <= i <= j <= len(cs)
746# try:
747# return _wrapped.Math.polyval(j - i - 1, cs, i, x)
748# except AttributeError:
749# s, t = cs[i], _0_0
750# for c in cs[i+1:j]:
751# s, t = _sum2_(s * x, t * x, c)
752# return s # + t
753 s = cs[i]
754 i += 1
755 if x and i < j:
756 s, _ = _sum2_(s, _0_0, x=x, *cs[i:j])
757 return s # + t
760def _remainder(x, y):
761 '''Remainder of C{x / y}.
763 @return: Remainder in the range M{[-y / 2, y / 2]}, preserving signed 0.0.
764 '''
765 try:
766 return _wrapped.Math.remainder(x, y)
767 except AttributeError:
768 return fremainder(x, y)
771if _K_2_0:
772 from math import cos as _cos, sin as _sin
774 def _sincos2(rad):
775 return _sin(rad), _cos(rad)
777 _signBit = _MODS.basics.signBit
778else:
779 _sincos2 = _MODS.utily.sincos2 # PYCHOK shared
781 def _signBit(x):
782 '''(INTERNAL) GeographicLib 1.52-.
783 '''
784 return x < 0
787def _sincos2d(deg):
788 '''Return sine and cosine of an angle in C{degrees}.
790 @return: 2-Tuple C{(sin(B{deg}), cos(B{deg}))}.
791 '''
792 try:
793 return _wrapped.Math.sincosd(deg)
794 except AttributeError:
795 return sincos2d(deg)
798def _sincos2de(deg, t):
799 '''Return sine and cosine of a corrected angle in C{degrees}.
801 @return: 2-Tuple C{(sin(B{deg}), cos(B{deg}))}.
802 '''
803 try:
804 return _wrapped.Math.sincosde(deg, t)
805 except AttributeError:
806 return sincos2d(deg, adeg=t)
809def _sum2(u, v): # mimick geomath.Math.sum, actually sum2
810 '''Error-free summation like C{geomath.Math.sum}.
812 @return: 2-Tuple C{(B{u} + B{v}, residual)}.
814 @note: The C{residual} can be the same as B{C{u}} or B{C{v}}.
816 @see: U{Algorithm 3.1<https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}.
817 '''
818 try:
819 return _wrapped.Math.sum(u, v)
820 except AttributeError:
821 s = u + v
822 r = s - v
823 t = s - r
824 # if Algorithm_3_1:
825 # t = (u - t) + (v + r)
826 # elif C_CPP: # Math::sum C/C++
827 # r -= u
828 # t -= v
829 # t += r
830 # t = -t
831 # else:
832 t = (u - r) + (v - t)
833 return s, t
836def _sum2_(s, t, *vs, **x):
837 '''Accumulate any B{C{vs}} into a previous C{_sum2(s, t)}.
839 @kwarg x: Optional polynomial C{B{x}=1} (C{scalar}).
841 @return: 2-Tuple C{(B{s} + B{t} + sum(B{vs}), residual)}.
843 @see: I{Karney's} C++ U{Accumulator<https://GeographicLib.SourceForge.io/
844 C++/doc/Accumulator_8hpp_source.html>} comments for more details and
845 function C{_sum2} above.
847 @note: NOT "error-free", see C{pygeodesy.test/testKarney.py}.
848 '''
849 x = _xkwds_get1(x, x=_1_0)
850 p = x != _1_0
852 _s2, _u0 = _sum2, unsigned0
853 for v in vs:
854 if p:
855 s *= x
856 t *= x
857 if v:
858 t, u = _s2(t, v) # start at the least-
859 if s:
860 s, t = _s2(s, t) # significant end
861 if s:
862 t += u # accumulate u into t
863# elif t: # s == 0 implies t == 0
864# raise _AssertionError(t=t, txt_not_=_0_)
865 else:
866 s = _u0(u) # result is u, t = 0
867 else:
868 s, t = _u0(t), u
869 return s, t
872def _tand(x):
873 '''Return C{tan(B{x})} in C{degrees}.
874 '''
875 try:
876 return _wrapped.Math.tand(x)
877 except AttributeError:
878 return tand(x)
881def _unroll2(lon1, lon2, wrap=False): # see .ellipsoidalBaseDI._intersects2
882 '''Unroll B{C{lon2 - lon1}} like C{geodesic.Geodesic.Inverse}.
884 @return: 2-Tuple C{(B{lon2} - B{lon1}, B{lon2})} with B{C{lon2}}
885 unrolled if B{C{wrap}} is C{True}, normalized otherwise.
886 '''
887 if wrap:
888 d, t = _diff182(lon1, lon2)
889 lon2, _ = _sum2_(d, t, lon1) # (lon1 + d) + t
890 else:
891 lon2 = _norm180(lon2)
892 return (lon2 - lon1), lon2
895def _unsigned2(x):
896 '''(INTERNAL) Unsign B{C{x}}.
897 '''
898 return (neg(x), True) if _signBit(x) else (x, False)
901__all__ += _ALL_DOCS(_CapsBase)
903# **) MIT License
904#
905# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
906#
907# Permission is hereby granted, free of charge, to any person obtaining a
908# copy of this software and associated documentation files (the "Software"),
909# to deal in the Software without restriction, including without limitation
910# the rights to use, copy, modify, merge, publish, distribute, sublicense,
911# and/or sell copies of the Software, and to permit persons to whom the
912# Software is furnished to do so, subject to the following conditions:
913#
914# The above copyright notice and this permission notice shall be included
915# in all copies or substantial portions of the Software.
916#
917# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
918# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
919# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
920# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
921# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
922# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
923# OTHER DEALINGS IN THE SOFTWARE.