Coverage for pygeodesy/geodesicx/gx.py: 93%
512 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-01-06 12:20 -0500
« prev ^ index » next coverage.py v7.6.1, created at 2025-01-06 12:20 -0500
2# -*- coding: utf-8 -*-
4u'''A pure Python version of I{Karney}'s C++ class U{GeodesicExact
5<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>}.
7Class L{GeodesicExact} follows the naming, methods and return values
8of class C{Geodesic} from I{Karney}'s Python U{geographiclib
9<https://GitHub.com/geographiclib/geographiclib-python>}.
11Copyright (C) U{Charles Karney<mailto:Karney@Alum.MIT.edu>} (2008-2024)
12and licensed under the MIT/X11 License. For more information, see the
13U{GeographicLib<https://GeographicLib.SourceForge.io>} documentation.
14'''
15# make sure int/int division yields float quotient
16from __future__ import division as _; del _ # PYCHOK semicolon
18# A copy of comments from Karney's C{GeodesicExact.cpp}:
19#
20# This is a reformulation of the geodesic problem. The
21# notation is as follows:
22# - at a general point (no suffix or 1 or 2 as suffix)
23# - phi = latitude
24# - lambda = longitude
25# - beta = latitude on auxiliary sphere
26# - omega = longitude on auxiliary sphere
27# - alpha = azimuth of great circle
28# - sigma = arc length along great circle
29# - s = distance
30# - tau = scaled distance (= sigma at multiples of PI/2)
31# - at northwards equator crossing
32# - beta = phi = 0
33# - omega = lambda = 0
34# - alpha = alpha0
35# - sigma = s = 0
36# - a 12 suffix means a difference, e.g., s12 = s2 - s1.
37# - s and c prefixes mean sin and cos
39from pygeodesy.basics import _copysign, _xinstanceof, _xor, unsigned0
40from pygeodesy.constants import EPS, EPS0, EPS02, MANT_DIG, NAN, PI, _EPSqrt, \
41 _SQRT2_2, isnan, _0_0, _0_001, _0_01, _0_1, _0_5, \
42 _1_0, _N_1_0, _1_75, _2_0, _N_2_0, _2__PI, _3_0, \
43 _4_0, _6_0, _8_0, _16_0, _90_0, _180_0, _1000_0
44from pygeodesy.datums import _earth_datum, _WGS84, _EWGS84
45# from pygeodesy.ellipsoids import _EWGS84 # from .datums
46from pygeodesy.errors import GeodesicError, _xkwds_pop2
47from pygeodesy.fmath import hypot as _hypot, Fmt
48from pygeodesy.fsums import fsumf_, fsum1f_
49from pygeodesy.geodesicx.gxbases import _cosSeries, _GeodesicBase, \
50 _sincos12, _sin1cos2, _sinf1cos2d, \
51 _TINY, _xnC4
52from pygeodesy.geodesicx.gxline import _GeodesicLineExact, _update_glXs
53from pygeodesy.interns import NN, _DOT_, _UNDER_
54from pygeodesy.karney import GDict, _around, _atan2d, Caps, _cbrt, _diff182, \
55 _fix90, _K_2_0, _norm2, _norm180, _polynomial, \
56 _signBit, _sincos2, _sincos2d, _sincos2de, _unsigned2
57from pygeodesy.lazily import _ALL_DOCS, _ALL_MODS as _MODS
58from pygeodesy.namedTuples import Destination3Tuple, Distance3Tuple
59from pygeodesy.props import deprecated_Property, Property, Property_RO, property_RO
60# from pygeodesy.streprs import Fmt # from .fmath
61from pygeodesy.utily import atan2, atan2d as _atan2d_reverse, _unrollon, \
62 _Wrap, wrap360
64from math import copysign, cos, degrees, fabs, radians, sqrt
66__all__ = ()
67__version__ = '24.11.24'
69_MAXIT1 = 20
70_MAXIT2 = 10 + _MAXIT1 + MANT_DIG # MANT_DIG == C++ digits
72# increased multiplier in defn of _TOL1 from 100 to 200 to fix Inverse
73# case 52.784459512564 0 -52.784459512563990912 179.634407464943777557
74# which otherwise failed for Visual Studio 10 (Release and Debug)
75_TOL0 = EPS
76_TOL1 = _TOL0 * -200 # negative
77_TOL2 = _EPSqrt # == sqrt(_TOL0)
78_TOL3 = _TOL2 * _0_1
79_TOLb = _TOL2 * _TOL0 # Check on bisection interval
80_THR1 = _TOL2 * _1000_0 + _1_0
82_TINY3 = _TINY * _3_0
83_TOL08 = _TOL0 * _8_0
84_TOL016 = _TOL0 * _16_0
87def _atan12(*sincos12, **sineg0):
88 '''(INTERNAL) Return C{ang12} in C{radians}.
89 '''
90 return atan2(*_sincos12(*sincos12, **sineg0))
93def _eTOL2(f):
94 # Using the auxiliary sphere solution with dnm computed at
95 # (bet1 + bet2) / 2, the relative error in the azimuth
96 # consistency check is sig12^2 * abs(f) * min(1, 1-f/2) / 2.
97 # (Error measured for 1/100 < b/a < 100 and abs(f) >= 1/1000.
99 # For a given f and sig12, the max error occurs for lines
100 # near the pole. If the old rule for computing dnm = (dn1
101 # + dn2)/2 is used, then the error increases by a factor of
102 # 2.) Setting this equal to epsilon gives sig12 = etol2.
104 # Here 0.1 is a safety factor (error decreased by 100) and
105 # max(0.001, abs(f)) stops etol2 getting too large in the
106 # nearly spherical case.
107 t = min(_1_0, _1_0 - f * _0_5) * max(_0_001, fabs(f)) * _0_5
108 return _TOL3 / (sqrt(t) if t > EPS02 else EPS0)
111class _PDict(GDict):
112 '''(INTERNAL) Parameters passed around in C{._GDictInverse} and
113 optionally returned when C{GeodesicExact.debug} is C{True}.
114 '''
115 def set_sigs(self, ssig1, csig1, ssig2, csig2):
116 '''Update the C{sig1} and C{sig2} parameters.
117 '''
118 self.set_(ssig1=ssig1, csig1=csig1, sncndn1=(ssig1, csig1, self.dn1), # PYCHOK dn1
119 ssig2=ssig2, csig2=csig2, sncndn2=(ssig2, csig2, self.dn2)) # PYCHOK dn2
121 def toGDict(self): # PYCHOK no cover
122 '''Return as C{GDict} without attrs C{sncndn1} and C{sncndn2}.
123 '''
124 def _rest(sncndn1=None, sncndn2=None, **rest): # PYCHOK sncndn* not used
125 return GDict(rest)
127 return _rest(**self)
130class GeodesicExact(_GeodesicBase):
131 '''A pure Python version of I{Karney}'s C++ class U{GeodesicExact
132 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>},
133 modeled after I{Karney}'s Python class U{geodesic.Geodesic<https://GitHub.com/
134 geographiclib/geographiclib-python>}.
135 '''
136 _datum = _WGS84
137 _nC4 = 30 # default C4order
139 def __init__(self, a_ellipsoid=_EWGS84, f=None, C4order=None, **name_C4Order): # for backward compatibility
140 '''New L{GeodesicExact} instance.
142 @arg a_ellipsoid: An ellipsoid (L{Ellipsoid}) or datum (L{Datum}) or
143 the equatorial radius of the ellipsoid (C{scalar},
144 conventionally in C{meter}), see B{C{f}}.
145 @arg f: The flattening of the ellipsoid (C{scalar}) if B{C{a_ellipsoid}}
146 is specified as C{scalar}.
147 @kwarg C4order: Optional series expansion order (C{int}), see property
148 L{C4order}, default C{30}.
149 @kwarg name_C4Order: Optional C{B{name}=NN} (C{str}) and the DEPRECATED
150 keyword argument C{C4Order}, use B{C{C4order}} instead.
152 @raise GeodesicError: Invalid B{C{C4order}}.
153 '''
154 if name_C4Order:
155 C4order, name = _xkwds_pop2(name_C4Order, C4Order=C4order)
156 if name:
157 self.name = name
158 else:
159 name = {} # name_C4Order
161 _earth_datum(self, a_ellipsoid, f=f, **name)
162 if C4order: # XXX private copy, always?
163 self.C4order = C4order
165 @Property_RO
166 def a(self):
167 '''Get the I{equatorial} radius, semi-axis (C{meter}).
168 '''
169 return self.ellipsoid.a
171 def ArcDirect(self, lat1, lon1, azi1, a12, outmask=Caps.STANDARD):
172 '''Solve the I{Direct} geodesic problem in terms of (spherical) arc length.
174 @arg lat1: Latitude of the first point (C{degrees}).
175 @arg lon1: Longitude of the first point (C{degrees}).
176 @arg azi1: Azimuth at the first point (compass C{degrees}).
177 @arg a12: Arc length between the points (C{degrees}), can be negative.
178 @kwarg outmask: Bit-or'ed combination of L{Caps} values specifying
179 the quantities to be returned.
181 @return: A L{GDict} with up to 12 items C{lat1, lon1, azi1, lat2,
182 lon2, azi2, m12, a12, s12, M12, M21, S12} with C{lat1},
183 C{lon1}, C{azi1} and arc length C{a12} always included.
185 @see: C++ U{GeodesicExact.ArcDirect
186 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>}
187 and Python U{Geodesic.ArcDirect<https://GeographicLib.SourceForge.io/Python/doc/code.html>}.
188 '''
189 return self._GDictDirect(lat1, lon1, azi1, True, a12, outmask)
191 def ArcDirectLine(self, lat1, lon1, azi1, a12, caps=Caps.ALL, **name):
192 '''Define a L{GeodesicLineExact} in terms of the I{direct} geodesic problem and as arc length.
194 @arg lat1: Latitude of the first point (C{degrees}).
195 @arg lon1: Longitude of the first point (C{degrees}).
196 @arg azi1: Azimuth at the first point (compass C{degrees}).
197 @arg a12: Arc length between the points (C{degrees}), can be negative.
198 @kwarg caps: Bit-or'ed combination of L{Caps} values specifying
199 the capabilities the L{GeodesicLineExact} instance
200 should possess, i.e., which quantities can be
201 returned by calls to L{GeodesicLineExact.Position}
202 and L{GeodesicLineExact.ArcPosition}.
203 @kwarg name: Optional C{B{name}=NN} (C{str}).
205 @return: A L{GeodesicLineExact} instance.
207 @note: The third point of the L{GeodesicLineExact} is set to correspond
208 to the second point of the I{Inverse} geodesic problem.
210 @note: Latitude B{C{lat1}} should in the range C{[-90, +90]}.
212 @see: C++ U{GeodesicExact.ArcDirectLine
213 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>} and
214 Python U{Geodesic.ArcDirectLine<https://GeographicLib.SourceForge.io/Python/doc/code.html>}.
215 '''
216 return GeodesicLineExact(self, lat1, lon1, azi1, caps=caps, **name)._GenSet(self._debug, a12=a12)
218 def Area(self, polyline=False, **name):
219 '''Set up a L{GeodesicAreaExact} to compute area and
220 perimeter of a polygon.
222 @kwarg polyline: If C{True}, compute the perimeter only, otherwise
223 the perimeter and area (C{bool}).
224 @kwarg name: Optional C{B{name}=NN} (C{str}).
226 @return: A L{GeodesicAreaExact} instance.
228 @note: The B{C{debug}} setting is passed as C{verbose}
229 to the returned L{GeodesicAreaExact} instance.
230 '''
231 gaX = _MODS.geodesicx.GeodesicAreaExact(self, polyline=polyline,
232 name=self._name__(name))
233 if self.debug:
234 gaX.verbose = True
235 return gaX
237 @Property_RO
238 def b(self):
239 '''Get the ellipsoid's I{polar} radius, semi-axis (C{meter}).
240 '''
241 return self.ellipsoid.b
243 @Property_RO
244 def c2x(self):
245 '''Get the ellipsoid's I{authalic} earth radius I{squared} (C{meter} I{squared}).
246 '''
247 # The Geodesic class substitutes atanh(sqrt(e2)) for asinh(sqrt(ep2))
248 # in the definition of _c2. The latter is more accurate for very
249 # oblate ellipsoids (which the Geodesic class does not handle). Of
250 # course, the area calculation in GeodesicExact is still based on a
251 # series and only holds for moderately oblate (or prolate) ellipsoids.
252 return self.ellipsoid.c2x
254 c2 = c2x # in this particular case
256 def C4f(self, eps):
257 '''Evaluate the C{C4x} coefficients for B{C{eps}}.
259 @arg eps: Polynomial factor (C{float}).
261 @return: C{C4order}-Tuple of C{C4x(B{eps})} coefficients.
262 '''
263 def _c4(nC4, C4x):
264 i, x, e = 0, _1_0, eps
265 _p = _polynomial
266 for r in range(nC4, 0, -1):
267 j = i + r
268 yield _p(e, C4x, i, j) * x
269 x *= e
270 i = j
271 # assert i == (nC4 * (nC4 + 1)) // 2
273 return tuple(_c4(self._nC4, self._C4x))
275 def _C4f_k2(self, k2): # in ._GDictInverse and gxline._GeodesicLineExact._C4a
276 '''(INTERNAL) Compute C{eps} from B{C{k2}} and invoke C{C4f}.
277 '''
278 return self.C4f(k2 / fsumf_(_2_0, sqrt(k2 + _1_0) * _2_0, k2))
280 @Property
281 def C4order(self):
282 '''Get the series expansion order (C{int}, 24, 27 or 30).
283 '''
284 return self._nC4
286 @C4order.setter # PYCHOK .setter!
287 def C4order(self, order):
288 '''Set the series expansion order (C{int}, 24, 27 or 30).
290 @raise GeodesicError: Invalid B{C{order}}.
291 '''
292 _xnC4(C4order=order)
293 if self._nC4 != order:
294 GeodesicExact._C4x._update(self)
295 _update_glXs(self) # zap cached _GeodesicLineExact attrs _B41, _C4a
296 self._nC4 = order
298 @deprecated_Property
299 def C4Order(self):
300 '''DEPRECATED, use property C{C4order}.
301 '''
302 return self.C4order
304 @C4Order.setter # PYCHOK .setter!
305 def C4Order(self, order):
306 '''DEPRECATED, use property C{C4order}.
307 '''
308 _xnC4(C4Order=order)
309 self.C4order = order
311 @Property_RO
312 def _C4x(self):
313 '''Get this ellipsoid's C{C4} coefficients, I{cached} tuple.
315 @see: Property L{C4order}.
316 '''
317 # see C4coeff() in GeographicLib.src.GeodesicExactC4.cpp
318 def _C4(nC4):
319 i, n, cs = 0, self.n, _C4coeffs(nC4)
320 _p = _polynomial
321 for r in range(nC4 + 1, 1, -1): # _reverange
322 for j in range(1, r):
323 j = j + i # (j - i - 1) order of polynomial
324 yield _p(n, cs, i, j) / cs[j]
325 i = j + 1
326 # assert i == (nC4 * (nC4 + 1) * (nC4 + 5)) // 6
328 return tuple(_C4(self._nC4)) # 3rd flattening
330 @property_RO
331 def datum(self):
332 '''Get the datum (C{Datum}).
333 '''
334 return self._datum
336 def Direct(self, lat1, lon1, azi1, s12=0, outmask=Caps.STANDARD):
337 '''Solve the I{Direct} geodesic problem
339 @arg lat1: Latitude of the first point (C{degrees}).
340 @arg lon1: Longitude of the first point (C{degrees}).
341 @arg azi1: Azimuth at the first point (compass C{degrees}).
342 @arg s12: Distance between the points (C{meter}), can be negative.
343 @kwarg outmask: Bit-or'ed combination of L{Caps} values specifying
344 the quantities to be returned.
346 @return: A L{GDict} with up to 12 items C{lat1, lon1, azi1, lat2,
347 lon2, azi2, m12, a12, s12, M12, M21, S12} with C{lat1},
348 C{lon1}, C{azi1} and distance C{s12} always included.
350 @see: C++ U{GeodesicExact.Direct
351 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>}
352 and Python U{Geodesic.Direct<https://GeographicLib.SourceForge.io/Python/doc/code.html>}.
353 '''
354 return self._GDictDirect(lat1, lon1, azi1, False, s12, outmask)
356 def Direct3(self, lat1, lon1, azi1, s12): # PYCHOK outmask
357 '''Return the destination lat, lon and reverse azimuth
358 (final bearing) in C{degrees}.
360 @return: L{Destination3Tuple}C{(lat, lon, final)}.
361 '''
362 r = self._GDictDirect(lat1, lon1, azi1, False, s12, Caps._AZIMUTH_LATITUDE_LONGITUDE)
363 return Destination3Tuple(r.lat2, r.lon2, r.azi2) # no iteration
365 def _DirectLine(self, ll1, azi12, s12=0, **caps_name):
366 '''(INTERNAL) Short-cut version.
367 '''
368 return self.DirectLine(ll1.lat, ll1.lon, azi12, s12, **caps_name)
370 def DirectLine(self, lat1, lon1, azi1, s12, caps=Caps.STANDARD, **name):
371 '''Define a L{GeodesicLineExact} in terms of the I{direct} geodesic problem and as distance.
373 @arg lat1: Latitude of the first point (C{degrees}).
374 @arg lon1: Longitude of the first point (C{degrees}).
375 @arg azi1: Azimuth at the first point (compass C{degrees}).
376 @arg s12: Distance between the points (C{meter}), can be negative.
377 @kwarg caps: Bit-or'ed combination of L{Caps} values specifying
378 the capabilities the L{GeodesicLineExact} instance
379 should possess, i.e., which quantities can be
380 returned by calls to L{GeodesicLineExact.Position}.
381 @kwarg name: Optional C{B{name}=NN} (C{str}).
383 @return: A L{GeodesicLineExact} instance.
385 @note: The third point of the L{GeodesicLineExact} is set to correspond
386 to the second point of the I{Inverse} geodesic problem.
388 @note: Latitude B{C{lat1}} should in the range C{[-90, +90]}.
390 @see: C++ U{GeodesicExact.DirectLine
391 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>} and
392 Python U{Geodesic.DirectLine<https://GeographicLib.SourceForge.io/Python/doc/code.html>}.
393 '''
394 return GeodesicLineExact(self, lat1, lon1, azi1, caps=caps, **name)._GenSet(self._debug, s12=s12)
396 def _dn(self, sbet, cbet): # in gxline._GeodesicLineExact.__init__
397 '''(INTERNAL) Helper.
398 '''
399 if self.f < 0: # PYCHOK no cover
400 dn = sqrt(_1_0 - cbet**2 * self.e2) / self.f1
401 else:
402 dn = sqrt(_1_0 + sbet**2 * self.ep2)
403 return dn
405 @Property_RO
406 def e2(self):
407 '''Get the ellipsoid's I{(1st) eccentricity squared} (C{float}), M{f * (2 - f)}.
408 '''
409 return self.ellipsoid.e2
411 @Property_RO
412 def _e2a2(self):
413 '''(INTERNAL) Cache M{E.e2 * E.a2}.
414 '''
415 return self.e2 * self.ellipsoid.a2
417 @Property_RO
418 def _e2_f1(self):
419 '''(INTERNAL) Cache M{E.e2 * E.f1}.
420 '''
421 return self.e2 / self.f1
423 @Property_RO
424 def _eF(self):
425 '''(INTERNAL) Get the elliptic function, aka C{.E}.
426 '''
427 return _MODS.elliptic.Elliptic(k2=-self.ep2)
429 def _eF_reset_cHe2_f1(self, x, y):
430 '''(INTERNAL) Reset elliptic function and return M{cH * e2 / f1 * ...}.
431 '''
432 self._eF_reset_k2(x)
433 return y * self._eF.cH * self._e2_f1
435 def _eF_reset_k2(self, x):
436 '''(INTERNAL) Reset elliptic function and return C{k2}.
437 '''
438 ep2 = self.ep2
439 k2 = x**2 * ep2 # see .gxline._GeodesicLineExact._eF
440 self._eF.reset(k2=-k2, alpha2=-ep2) # kp2, alphap2 defaults
441 _update_glXs(self) # zap cached/memoized _GeodesicLineExact attrs
442 return k2
444 @Property_RO
445 def ellipsoid(self):
446 '''Get the ellipsoid (C{Ellipsoid}).
447 '''
448 return self.datum.ellipsoid
450 @Property_RO
451 def ep2(self):
452 '''Get the ellipsoid's I{2nd eccentricity squared} (C{float}), M{e2 / (1 - e2)}.
453 '''
454 return self.ellipsoid.e22 # == self.e2 / self.f1**2
456 e22 = ep2 # for ellipsoid compatibility
458 @Property_RO
459 def _eTOL2(self):
460 '''(INTERNAL) The si12 threshold for "really short".
461 '''
462 return _eTOL2(self.f)
464 @Property_RO
465 def flattening(self):
466 '''Get the C{ellipsoid}'s I{flattening} (C{scalar}), M{(a - b) / a}, C{0} for spherical, negative for prolate.
467 '''
468 return self.ellipsoid.f
470 f = flattening
472 @Property_RO
473 def f1(self): # in .css.CassiniSoldner.reset
474 '''Get the C{ellipsoid}'s I{1 - flattening} (C{float}).
475 '''
476 return self.ellipsoid.f1
478 @Property_RO
479 def _f180(self):
480 '''(INTERNAL) Cached/memoized.
481 '''
482 return self.f * _180_0
484 def _GDictDirect(self, lat1, lon1, azi1, arcmode, s12_a12, outmask=Caps.STANDARD):
485 '''(INTERNAL) As C{_GenDirect}, but returning a L{GDict}.
487 @return: A L{GDict} ...
488 '''
489 C = outmask if arcmode else (outmask | Caps.DISTANCE_IN)
490 glX = self.Line(lat1, lon1, azi1, C | Caps.LINE_OFF)
491 return glX._GDictPosition(arcmode, s12_a12, outmask)
493 def _GDictInverse(self, lat1, lon1, lat2, lon2, outmask=Caps.STANDARD): # MCCABE 33, 41 vars
494 '''(INTERNAL) As C{_GenInverse}, but returning a L{GDict}.
496 @return: A L{GDict} ...
497 '''
498 Cs = Caps
499 if self._debug: # PYCHOK no cover
500 outmask |= Cs._DEBUG_INVERSE & self._debug
501 outmask &= Cs._OUT_MASK # incl. _SALP_CALPs_ and _DEBUG_
502 # compute longitude difference carefully (with _diff182):
503 # result is in [-180, +180] but -180 is only for west-going
504 # geodesics, +180 is for east-going and meridional geodesics
505 lon12, lon12s = _diff182(lon1, lon2)
506 # see C{result} from geographiclib.geodesic.Inverse
507 if (outmask & Cs.LONG_UNROLL): # == (lon1 + lon12) + lon12s
508 r = GDict(lon1=lon1, lon2=fsumf_(lon1, lon12, lon12s))
509 elif (outmask & Cs.LONGITUDE):
510 r = GDict(lon1=_norm180(lon1), lon2=_norm180(lon2))
511 else:
512 r = GDict()
513 if _K_2_0: # GeographicLib 2.0
514 # make longitude difference positive
515 lon12, lon_ = _unsigned2(lon12)
516 if lon_:
517 lon12s = -lon12s
518 lam12 = radians(lon12)
519 # calculate sincosd(_around(lon12 + correction))
520 slam12, clam12 = _sincos2de(lon12, lon12s)
521 # supplementary longitude difference
522 lon12s = fsumf_(_180_0, -lon12, -lon12s)
523 else: # GeographicLib 1.52
524 # make longitude difference positive and if very close
525 # to being on the same half-meridian, then make it so.
526 if lon12 < 0: # _signBit(lon12)
527 lon_, lon12 = True, -_around(lon12)
528 lon12s = _around(fsumf_(_180_0, -lon12, lon12s))
529 else:
530 lon_, lon12 = False, _around(lon12)
531 lon12s = _around(fsumf_(_180_0, -lon12, -lon12s))
532 lam12 = radians(lon12)
533 if lon12 > _90_0:
534 slam12, clam12 = _sincos2d(lon12s)
535 clam12 = -clam12
536 else:
537 slam12, clam12 = _sincos2(lam12)
538 # If really close to the equator, treat as on equator.
539 lat1 = _around(_fix90(lat1))
540 lat2 = _around(_fix90(lat2))
541 if (outmask & Cs.LATITUDE):
542 r.set_(lat1=lat1, lat2=lat2)
543 # Swap points so that point with higher (abs) latitude is
544 # point 1. If one latitude is a NAN, then it becomes lat1.
545 swap_ = fabs(lat1) < fabs(lat2) or isnan(lat2)
546 if swap_:
547 lat1, lat2 = lat2, lat1
548 lon_ = not lon_
549 if _signBit(lat1):
550 lat_ = False # note, False
551 else: # make lat1 <= -0
552 lat_ = True # note, True
553 lat1, lat2 = -lat1, -lat2
554 # Now 0 <= lon12 <= 180, -90 <= lat1 <= -0 and lat1 <= lat2 <= -lat1
555 # and lat_, lon_, swap_ register the transformation to bring the
556 # coordinates to this canonical form, where False means no change
557 # made. We make these transformations so that there are few cases
558 # to check, e.g., on verifying quadrants in atan2. In addition,
559 # this enforces some symmetries in the results returned.
561 # Initialize for the meridian. No longitude calculation is done in
562 # this case to let the parameter default to 0.
563 sbet1, cbet1 = _sinf1cos2d(lat1, self.f1)
564 sbet2, cbet2 = _sinf1cos2d(lat2, self.f1)
565 # If cbet1 < -sbet1, then cbet2 - cbet1 is a sensitive measure
566 # of the |bet1| - |bet2|. Alternatively (cbet1 >= -sbet1),
567 # abs(sbet2) + sbet1 is a better measure. This logic is used
568 # in assigning calp2 in _Lambda6. Sometimes these quantities
569 # vanish and in that case we force bet2 = +/- bet1 exactly. An
570 # example where is is necessary is the inverse problem
571 # 48.522876735459 0 -48.52287673545898293 179.599720456223079643
572 # which failed with Visual Studio 10 (Release and Debug)
573 if cbet1 < -sbet1:
574 if cbet2 == cbet1:
575 sbet2 = copysign(sbet1, sbet2)
576 elif fabs(sbet2) == -sbet1:
577 cbet2 = cbet1
579 p = _PDict(sbet1=sbet1, cbet1=cbet1, dn1=self._dn(sbet1, cbet1),
580 sbet2=sbet2, cbet2=cbet2, dn2=self._dn(sbet2, cbet2))
582 _meridian = _b = True # i.e. not meridian, not b
583 if lat1 == -90 or slam12 == 0:
584 # Endpoints are on a single full meridian,
585 # so the geodesic might lie on a meridian.
586 salp1, calp1 = slam12, clam12 # head to target lon
587 salp2, calp2 = _0_0, _1_0 # then head north
588 # tan(bet) = tan(sig) * cos(alp)
589 p.set_sigs(sbet1, calp1 * cbet1, sbet2, calp2 * cbet2)
590 # sig12 = sig2 - sig1
591 sig12 = _atan12(sbet1, p.csig1, sbet2, p.csig2, sineg0=True) # PYCHOK csig*
592 s12x, m12x, _, \
593 M12, M21 = self._Length5(sig12, outmask | Cs.REDUCEDLENGTH, p)
594 # Add the check for sig12 since zero length geodesics
595 # might yield m12 < 0. Test case was
596 # echo 20.001 0 20.001 0 | GeodSolve -i
597 # In fact, we will have sig12 > PI/2 for meridional
598 # geodesic which is not a shortest path.
599 if m12x >= 0 or sig12 < _1_0:
600 # Need at least 2 to handle 90 0 90 180
601 # Prevent negative s12 or m12 from geographiclib 1.52
602 if sig12 < _TINY3 or (sig12 < _TOL0 and (s12x < 0 or m12x < 0)):
603 sig12 = m12x = s12x = _0_0
604 else:
605 _b = False # apply .b to s12x, m12x
606 _meridian = False
607 C = 1
608 # else: # m12 < 0, prolate and too close to anti-podal
609 # _meridian = True
610 a12 = _0_0 # if _b else degrees(sig12)
612 if _meridian:
613 _b = sbet1 == 0 and (self.f <= 0 or lon12s >= self._f180) # and sbet2 == 0
614 if _b: # Geodesic runs along equator
615 calp1 = calp2 = _0_0
616 salp1 = salp2 = _1_0
617 sig12 = lam12 / self.f1 # == omg12
618 somg12, comg12 = _sincos2(sig12)
619 m12x = self.b * somg12
620 s12x = self.a * lam12
621 M12 = M21 = comg12
622 a12 = lon12 / self.f1
623 C = 2
624 else:
625 # Now point1 and point2 belong within a hemisphere bounded by a
626 # meridian and geodesic is neither meridional or equatorial.
627 p.set_(slam12=slam12, clam12=clam12)
628 # Figure a starting point for Newton's method
629 sig12, salp1, calp1, \
630 salp2, calp2, dnm = self._InverseStart6(lam12, p)
631 if sig12 is None: # use Newton's method
632 # pre-compute the constant _Lambda6 term, once
633 p.set_(bet12=None if cbet2 == cbet1 and fabs(sbet2) == -sbet1 else
634 (((cbet1 + cbet2) * (cbet2 - cbet1)) if cbet1 < -sbet1 else
635 ((sbet1 + sbet2) * (sbet1 - sbet2))))
636 sig12, salp1, calp1, \
637 salp2, calp2, domg12 = self._Newton6(salp1, calp1, p)
638 s12x, m12x, _, M12, M21 = self._Length5(sig12, outmask, p)
639 if (outmask & Cs.AREA):
640 # omg12 = lam12 - domg12
641 s, c = _sincos2(domg12)
642 somg12, comg12 = _sincos12(s, c, slam12, clam12)
643 C = 3 # Newton
644 else: # from _InverseStart6: dnm, salp*, calp*
645 C = 4 # Short lines
646 s, c = _sincos2(sig12 / dnm)
647 m12x = dnm**2 * s
648 s12x = dnm * sig12
649 M12 = M21 = c
650 if (outmask & Cs.AREA):
651 somg12, comg12 = _sincos2(lam12 / (self.f1 * dnm))
653 else: # _meridian is False
654 somg12 = comg12 = NAN
656 r.set_(a12=a12 if _b else degrees(sig12)) # in [0, 180]
658 if (outmask & Cs.DISTANCE):
659 r.set_(s12=unsigned0(s12x if _b else (self.b * s12x)))
661 if (outmask & Cs.REDUCEDLENGTH):
662 r.set_(m12=unsigned0(m12x if _b else (self.b * m12x)))
664 if (outmask & Cs.GEODESICSCALE):
665 if swap_:
666 M12, M21 = M21, M12
667 r.set_(M12=unsigned0(M12),
668 M21=unsigned0(M21))
670 if (outmask & Cs.AREA):
671 S12 = self._InverseArea(_meridian, salp1, calp1,
672 salp2, calp2,
673 somg12, comg12, p)
674 if _xor(swap_, lat_, lon_):
675 S12 = -S12
676 r.set_(S12=unsigned0(S12))
678 if (outmask & (Cs.AZIMUTH | Cs._SALP_CALPs_)):
679 if swap_:
680 salp1, salp2 = salp2, salp1
681 calp1, calp2 = calp2, calp1
682 if _xor(swap_, lon_):
683 salp1, salp2 = -salp1, -salp2
684 if _xor(swap_, lat_):
685 calp1, calp2 = -calp1, -calp2
687 if (outmask & Cs.AZIMUTH):
688 r.set_(azi1=_atan2d(salp1, calp1),
689 azi2=_atan2d_reverse(salp2, calp2, reverse=outmask & Cs.REVERSE2))
690 if (outmask & Cs._SALP_CALPs_):
691 r.set_(salp1=salp1, calp1=calp1,
692 salp2=salp2, calp2=calp2)
694 if (outmask & Cs._DEBUG_INVERSE): # PYCHOK no cover
695 E, eF = self.ellipsoid, self._eF
696 p.set_(C=C, a=self.a, f=self.f, f1=self.f1,
697 e=E.e, e2=self.e2, ep2=self.ep2,
698 c2=E.c2, c2x=self.c2x,
699 eFcD=eF.cD, eFcE=eF.cE, eFcH=eF.cH,
700 eFk2=eF.k2, eFa2=eF.alpha2)
701 p.update(r) # r overrides p
702 r = p.toGDict()
703 return self._iter2tion(r, **p)
705 def _GenDirect(self, lat1, lon1, azi1, arcmode, s12_a12, outmask=Caps.STANDARD):
706 '''(INTERNAL) The general I{Inverse} geodesic calculation.
708 @return: L{Direct9Tuple}C{(a12, lat2, lon2, azi2,
709 s12, m12, M12, M21, S12)}.
710 '''
711 r = self._GDictDirect(lat1, lon1, azi1, arcmode, s12_a12, outmask)
712 return r.toDirect9Tuple()
714 def _GenInverse(self, lat1, lon1, lat2, lon2, outmask=Caps.STANDARD):
715 '''(INTERNAL) The general I{Inverse} geodesic calculation.
717 @return: L{Inverse10Tuple}C{(a12, s12, salp1, calp1, salp2, calp2,
718 m12, M12, M21, S12)}.
719 '''
720 r = self._GDictInverse(lat1, lon1, lat2, lon2, outmask | Caps._SALP_CALPs_)
721 return r.toInverse10Tuple()
723 def _Inverse(self, ll1, ll2, wrap, **outmask):
724 '''(INTERNAL) Short-cut version, see .base.ellipsoidalDI.intersecant2.
725 '''
726 if wrap:
727 ll2 = _unrollon(ll1, _Wrap.point(ll2))
728 return self.Inverse(ll1.lat, ll1.lon, ll2.lat, ll2.lon, **outmask)
730 def Inverse(self, lat1, lon1, lat2, lon2, outmask=Caps.STANDARD):
731 '''Perform the I{Inverse} geodesic calculation.
733 @arg lat1: Latitude of the first point (C{degrees}).
734 @arg lon1: Longitude of the first point (C{degrees}).
735 @arg lat2: Latitude of the second point (C{degrees}).
736 @arg lon2: Longitude of the second point (C{degrees}).
737 @kwarg outmask: Bit-or'ed combination of L{Caps} values specifying
738 the quantities to be returned.
740 @return: A L{GDict} with up to 12 items C{lat1, lon1, azi1, lat2,
741 lon2, azi2, m12, a12, s12, M12, M21, S12} with C{lat1},
742 C{lon1}, C{azi1} and distance C{s12} always included.
744 @note: The third point of the L{GeodesicLineExact} is set to correspond
745 to the second point of the I{Inverse} geodesic problem.
747 @note: Both B{C{lat1}} and B{C{lat2}} should in the range C{[-90, +90]}.
749 @see: C++ U{GeodesicExact.InverseLine
750 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>} and
751 Python U{Geodesic.InverseLine<https://GeographicLib.SourceForge.io/Python/doc/code.html>}.
752 '''
753 return self._GDictInverse(lat1, lon1, lat2, lon2, outmask)
755 def Inverse1(self, lat1, lon1, lat2, lon2, wrap=False):
756 '''Return the non-negative, I{angular} distance in C{degrees}.
758 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll
759 B{C{lat2}} and B{C{lon2}} (C{bool}).
760 '''
761 # see .FrechetKarney.distance, .HausdorffKarney._distance
762 # and .HeightIDWkarney._distances
763 if wrap:
764 _, lat2, lon2 = _Wrap.latlon3(lat1, lat2, lon2, True) # _Geodesic.LONG_UNROLL
765 return fabs(self._GDictInverse(lat1, lon1, lat2, lon2, Caps.EMPTY).a12) # a12 always
767 def Inverse3(self, lat1, lon1, lat2, lon2): # PYCHOK outmask
768 '''Return the distance in C{meter} and the forward and
769 reverse azimuths (initial and final bearing) in C{degrees}.
771 @return: L{Distance3Tuple}C{(distance, initial, final)}.
772 '''
773 r = self._GDictInverse(lat1, lon1, lat2, lon2, Caps.AZIMUTH_DISTANCE)
774 return Distance3Tuple(r.s12, wrap360(r.azi1), wrap360(r.azi2),
775 iteration=r.iteration)
777 def _InverseLine(self, ll1, ll2, wrap, **caps_name):
778 '''(INTERNAL) Short-cut version.
779 '''
780 if wrap:
781 ll2 = _unrollon(ll1, _Wrap.point(ll2))
782 return self.InverseLine(ll1.lat, ll1.lon, ll2.lat, ll2.lon, **caps_name)
784 def InverseLine(self, lat1, lon1, lat2, lon2, caps=Caps.STANDARD, **name):
785 '''Define a L{GeodesicLineExact} in terms of the I{Inverse} geodesic problem.
787 @arg lat1: Latitude of the first point (C{degrees}).
788 @arg lon1: Longitude of the first point (C{degrees}).
789 @arg lat2: Latitude of the second point (C{degrees}).
790 @arg lon2: Longitude of the second point (C{degrees}).
791 @kwarg caps: Bit-or'ed combination of L{Caps} values specifying
792 the capabilities the L{GeodesicLineExact} instance
793 should possess, i.e., which quantities can be
794 returned by calls to L{GeodesicLineExact.Position}
795 and L{GeodesicLineExact.ArcPosition}.
796 @kwarg name: Optional C{B{name}=NN} (C{str}).
798 @return: A L{GeodesicLineExact} instance.
800 @note: The third point of the L{GeodesicLineExact} is set to correspond
801 to the second point of the I{Inverse} geodesic problem.
803 @note: Both B{C{lat1}} and B{C{lat2}} should in the range C{[-90, +90]}.
805 @see: C++ U{GeodesicExact.InverseLine
806 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>} and
807 Python U{Geodesic.InverseLine<https://GeographicLib.SourceForge.io/Python/doc/code.html>}.
808 '''
809 Cs = Caps
810 r = self._GDictInverse(lat1, lon1, lat2, lon2, caps | Cs._SALP_CALPs_)
811 return GeodesicLineExact(self, lat1, lon1, None, caps=caps, _s_calp1=(r.salp1, r.calp1),
812 **name)._GenSet(self._debug, **r)
814 def _InverseArea(self, _meridian, salp1, calp1, # PYCHOK 9 args
815 salp2, calp2,
816 somg12, comg12, p):
817 '''(INTERNAL) Split off from C{_GDictInverse} to reduce complexity/length.
819 @return: Area C{S12}.
820 '''
821 # from _Lambda6: sin(alp1) * cos(bet1) = sin(alp0), calp0 > 0
822 salp0, calp0 = _sin1cos2(salp1, calp1, p.sbet1, p.cbet1)
823 A4 = calp0 * salp0
824 if A4:
825 # from _Lambda6: tan(bet) = tan(sig) * cos(alp)
826 k2 = calp0**2 * self.ep2
827 C4a = self._C4f_k2(k2)
828 B41 = _cosSeries(C4a, *_norm2(p.sbet1, calp1 * p.cbet1))
829 B42 = _cosSeries(C4a, *_norm2(p.sbet2, calp2 * p.cbet2))
830 # multiplier = a^2 * e^2 * cos(alpha0) * sin(alpha0)
831 A4 *= self._e2a2
832 S12 = A4 * (B42 - B41)
833 else: # avoid problems with indeterminate sig1, sig2 on equator
834 A4 = B41 = B42 = k2 = S12 = _0_0
836 if (_meridian and # omg12 < 3/4 * PI
837 comg12 > -_SQRT2_2 and # lon diff not too big
838 (p.sbet2 - p.sbet1) < _1_75): # lat diff not too big
839 # use tan(Gamma/2) = tan(omg12/2) *
840 # (tan(bet1/2) + tan(bet2/2)) /
841 # (tan(bet1/2) * tan(bet2/2) + 1))
842 # with tan(x/2) = sin(x) / (1 + cos(x))
843 dbet1 = p.cbet1 + _1_0
844 dbet2 = p.cbet2 + _1_0
845 domg12 = comg12 + _1_0
846 salp12 = (p.sbet1 * dbet2 + dbet1 * p.sbet2) * somg12
847 calp12 = (p.sbet1 * p.sbet2 + dbet1 * dbet2) * domg12
848 alp12 = atan2(salp12, calp12) * _2_0
849 else:
850 # alp12 = alp2 - alp1, used in atan2, no need to normalize
851 salp12, calp12 = _sincos12(salp1, calp1, salp2, calp2)
852 # The right thing appears to happen if alp1 = +/-180 and
853 # alp2 = 0, viz salp12 = -0 and alp12 = -180. However,
854 # this depends on the sign being attached to 0 correctly.
855 # Following ensures the correct behavior.
856 if salp12 == 0 and calp12 < 0:
857 alp12 = _copysign(PI, calp1)
858 else:
859 alp12 = atan2(salp12, calp12)
861 p.set_(alp12=alp12, A4=A4, B41=B41, B42=B42, k2=k2)
862 return S12 + self.c2x * alp12
864 def _InverseStart6(self, lam12, p):
865 '''(INTERNAL) Return a starting point for Newton's method in
866 C{salp1} and C{calp1} indicated by C{sig12=None}. If
867 Newton's method doesn't need to be used, return also
868 C{salp2}, C{calp2}, C{dnm} and C{sig12} non-C{None}.
870 @return: 6-Tuple C{(sig12, salp1, calp1, salp2, calp2, dnm)}
871 and C{p.set_sigs} updated for Newton, C{sig12=None}.
872 '''
873 sig12 = None # use Newton
874 salp1 = calp1 = salp2 = calp2 = dnm = NAN
876 # bet12 = bet2 - bet1 in [0, PI)
877 sbet12, cbet12 = _sincos12(p.sbet1, p.cbet1, p.sbet2, p.cbet2)
878 shortline = cbet12 >= 0 and sbet12 < _0_5 and (p.cbet2 * lam12) < _0_5
879 if shortline:
880 # sin((bet1 + bet2)/2)^2 = (sbet1 + sbet2)^2 / (
881 # (cbet1 + cbet2)^2 + (sbet1 + sbet2)^2)
882 t = (p.sbet1 + p.sbet2)**2
883 s = t / ((p.cbet1 + p.cbet2)**2 + t)
884 dnm = sqrt(_1_0 + self.ep2 * s)
885 somg12, comg12 = _sincos2(lam12 / (self.f1 * dnm))
886 else:
887 somg12, comg12 = p.slam12, p.clam12
889 # bet12a = bet2 + bet1 in (-PI, 0], note -sbet1
890 sbet12a, cbet12a = _sincos12(-p.sbet1, p.cbet1, p.sbet2, p.cbet2)
892 c = fabs(comg12) + _1_0 # == (1 - comg12) if comg12 < 0
893 s = somg12**2 / c
894 t = p.sbet1 * p.cbet2 * s
895 salp1 = p.cbet2 * somg12
896 calp1 = (sbet12a - t) if comg12 < 0 else (sbet12 + t)
898 ssig12 = _hypot(salp1, calp1)
899 csig12 = p.sbet1 * p.sbet2 + p.cbet1 * p.cbet2 * comg12
901 if shortline and ssig12 < self._eTOL2: # really short lines
902 t = c if comg12 < 0 else s
903 salp2, calp2 = _norm2(somg12 * p.cbet1,
904 sbet12 - p.cbet1 * p.sbet2 * t)
905 sig12 = atan2(ssig12, csig12) # do not use Newton
907 elif (self._n_0_1 or # Skip astroid calc if too eccentric
908 csig12 >= 0 or ssig12 >= (p.cbet1**2 * self._n6PI)):
909 pass # nothing to do, 0th order spherical approximation OK
911 else:
912 # Scale lam12 and bet2 to x, y coordinate system where antipodal
913 # point is at origin and singular point is at y = 0, x = -1
914 lam12x = atan2(-p.slam12, -p.clam12) # lam12 - PI
915 f = self.f
916 if f < 0: # PYCHOK no cover
917 # ssig1=sbet1, csig1=-cbet1, ssig2=sbet2, csig2=cbet2
918 p.set_sigs(p.sbet1, -p.cbet1, p.sbet2, p.cbet2)
919 # if lon12 = 180, this repeats a calculation made in Inverse
920 _, m12b, m0, _, _ = self._Length5(atan2(sbet12a, cbet12a) + PI,
921 Caps.REDUCEDLENGTH, p)
922 t = p.cbet1 * PI # x = dlat, y = dlon
923 x = m12b / (t * p.cbet2 * m0) - _1_0
924 sca = (sbet12a / (x * p.cbet1)) if x < -_0_01 else (-f * t)
925 y = lam12x / sca
926 else: # f >= 0, however f == 0 does not get here
927 sca = self._eF_reset_cHe2_f1(p.sbet1, p.cbet1 * _2_0)
928 x = lam12x / sca # dlon
929 y = sbet12a / (sca * p.cbet1) # dlat
931 if y > _TOL1 and x > -_THR1: # strip near cut
932 if f < 0: # PYCHOK no cover
933 calp1 = max( _0_0, x) if x > _TOL1 else max(_N_1_0, x)
934 salp1 = sqrt(_1_0 - calp1**2)
935 else:
936 salp1 = min( _1_0, -x)
937 calp1 = -sqrt(_1_0 - salp1**2)
938 else:
939 # Estimate alp1, by solving the astroid problem.
940 #
941 # Could estimate alpha1 = theta + PI/2, directly, i.e.,
942 # calp1 = y/k; salp1 = -x/(1+k); for _f >= 0
943 # calp1 = x/(1+k); salp1 = -y/k; for _f < 0 (need to check)
944 #
945 # However, it's better to estimate omg12 from astroid and use
946 # spherical formula to compute alp1. This reduces the mean
947 # number of Newton iterations for astroid cases from 2.24
948 # (min 0, max 6) to 2.12 (min 0, max 5). The changes in the
949 # number of iterations are as follows:
950 #
951 # change percent
952 # 1 5
953 # 0 78
954 # -1 16
955 # -2 0.6
956 # -3 0.04
957 # -4 0.002
958 #
959 # The histogram of iterations is (m = number of iterations
960 # estimating alp1 directly, n = number of iterations
961 # estimating via omg12, total number of trials = 148605):
962 #
963 # iter m n
964 # 0 148 186
965 # 1 13046 13845
966 # 2 93315 102225
967 # 3 36189 32341
968 # 4 5396 7
969 # 5 455 1
970 # 6 56 0
971 #
972 # omg12 is near PI, estimate work with omg12a = PI - omg12
973 k = _Astroid(x, y)
974 sca *= (y * (k + _1_0) / k) if f < 0 else \
975 (x * k / (k + _1_0))
976 s, c = _sincos2(-sca) # omg12a
977 # update spherical estimate of alp1 using omg12 instead of lam12
978 salp1 = p.cbet2 * s
979 calp1 = sbet12a - s * salp1 * p.sbet1 / (c + _1_0) # c = -c
981 # sanity check on starting guess. Backwards check allows NaN through.
982 salp1, calp1 = _norm2(salp1, calp1) if salp1 > 0 else (_1_0, _0_0)
984 return sig12, salp1, calp1, salp2, calp2, dnm
986 def _Lambda6(self, salp1, calp1, diffp, p):
987 '''(INTERNAL) Helper.
989 @return: 6-Tuple C{(lam12, sig12, salp2, calp2, domg12,
990 dlam12} and C{p.set_sigs} updated.
991 '''
992 eF = self._eF
993 f1 = self.f1
995 if p.sbet1 == calp1 == 0: # PYCHOK no cover
996 # Break degeneracy of equatorial line
997 calp1 = -_TINY
999 # sin(alp1) * cos(bet1) = sin(alp0), # calp0 > 0
1000 salp0, calp0 = _sin1cos2(salp1, calp1, p.sbet1, p.cbet1)
1001 # tan(bet1) = tan(sig1) * cos(alp1)
1002 # tan(omg1) = sin(alp0) * tan(sig1)
1003 # = sin(bet1) * tan(alp1)
1004 somg1 = salp0 * p.sbet1
1005 comg1 = calp1 * p.cbet1
1006 ssig1, csig1 = _norm2(p.sbet1, comg1)
1007 # Without normalization we have schi1 = somg1
1008 cchi1 = f1 * p.dn1 * comg1
1010 # Enforce symmetries in the case abs(bet2) = -bet1.
1011 # Need to be careful about this case, since this can
1012 # yield singularities in the Newton iteration.
1013 # sin(alp2) * cos(bet2) = sin(alp0)
1014 salp2 = (salp0 / p.cbet2) if p.cbet2 != p.cbet1 else salp1
1015 # calp2 = sqrt(1 - sq(salp2))
1016 # = sqrt(sq(calp0) - sq(sbet2)) / cbet2
1017 # and subst for calp0 and rearrange to give (choose
1018 # positive sqrt to give alp2 in [0, PI/2]).
1019 calp2 = fabs(calp1) if p.bet12 is None else (
1020 sqrt((calp1 * p.cbet1)**2 + p.bet12) / p.cbet2)
1021 # tan(bet2) = tan(sig2) * cos(alp2)
1022 # tan(omg2) = sin(alp0) * tan(sig2).
1023 somg2 = salp0 * p.sbet2
1024 comg2 = calp2 * p.cbet2
1025 ssig2, csig2 = _norm2(p.sbet2, comg2)
1026 # without normalization we have schi2 = somg2
1027 cchi2 = f1 * p.dn2 * comg2
1029 # omg12 = omg2 - omg1, limit to [0, PI]
1030 somg12, comg12 = _sincos12(somg1, comg1, somg2, comg2, sineg0=True)
1031 # chi12 = chi2 - chi1, limit to [0, PI]
1032 schi12, cchi12 = _sincos12(somg1, cchi1, somg2, cchi2, sineg0=True)
1034 p.set_sigs(ssig1, csig1, ssig2, csig2)
1035 # sig12 = sig2 - sig1, limit to [0, PI]
1036 sig12 = _atan12(ssig1, csig1, ssig2, csig2, sineg0=True)
1038 eta12 = self._eF_reset_cHe2_f1(calp0, salp0) * _2__PI # then ...
1039 eta12 *= fsum1f_(eF.deltaH(*p.sncndn2),
1040 -eF.deltaH(*p.sncndn1), sig12)
1041 # eta = chi12 - lam12
1042 lam12 = _atan12(p.slam12, p.clam12, schi12, cchi12) - eta12
1043 # domg12 = chi12 - omg12 - deta12
1044 domg12 = _atan12( somg12, comg12, schi12, cchi12) - eta12
1046 dlam12 = NAN # dv > 0 in ._Newton6
1047 if diffp:
1048 d = calp2 * p.cbet2
1049 if d:
1050 _, dlam12, _, _, _ = self._Length5(sig12, Caps.REDUCEDLENGTH, p)
1051 dlam12 *= f1 / d
1052 elif p.sbet1:
1053 dlam12 = -f1 * p.dn1 * _2_0 / p.sbet1
1055 # p.set_(deta12=-eta12, lam12=lam12)
1056 return lam12, sig12, salp2, calp2, domg12, dlam12
1058 def _Length5(self, sig12, outmask, p):
1059 '''(INTERNAL) Return M{m12b = (reduced length) / self.b} and
1060 calculate M{s12b = distance / self.b} and M{m0}, the
1061 coefficient of secular term in expression for reduced
1062 length and the geodesic scales C{M12} and C{M21}.
1064 @return: 5-Tuple C{(s12b, m12b, m0, M12, M21)}.
1065 '''
1066 s12b = m12b = m0 = M12 = M21 = NAN
1068 Cs = Caps
1069 eF = self._eF
1071 # outmask &= Cs._OUT_MASK
1072 if (outmask & Cs.DISTANCE):
1073 # Missing a factor of self.b
1074 s12b = eF.cE * _2__PI * fsum1f_(eF.deltaE(*p.sncndn2),
1075 -eF.deltaE(*p.sncndn1), sig12)
1077 if (outmask & Cs._REDUCEDLENGTH_GEODESICSCALE):
1078 m0x = -eF.k2 * eF.cD * _2__PI
1079 J12 = -m0x * fsum1f_(eF.deltaD(*p.sncndn2),
1080 -eF.deltaD(*p.sncndn1), sig12)
1081 if (outmask & Cs.REDUCEDLENGTH):
1082 m0 = m0x
1083 # Missing a factor of self.b. Add parens around
1084 # (csig1 * ssig2) and (ssig1 * csig2) to ensure
1085 # accurate cancellation for coincident points.
1086 m12b = fsum1f_(p.dn2 * (p.csig1 * p.ssig2),
1087 -p.dn1 * (p.ssig1 * p.csig2),
1088 J12 * (p.csig1 * p.csig2))
1089 if (outmask & Cs.GEODESICSCALE):
1090 M12 = M21 = p.ssig1 * p.ssig2 + \
1091 p.csig1 * p.csig2
1092 t = (p.cbet1 - p.cbet2) * self.ep2 * \
1093 (p.cbet1 + p.cbet2) / (p.dn1 + p.dn2)
1094 M12 += (p.ssig2 * t + p.csig2 * J12) * p.ssig1 / p.dn1
1095 M21 -= (p.ssig1 * t + p.csig1 * J12) * p.ssig2 / p.dn2
1097 return s12b, m12b, m0, M12, M21
1099 def Line(self, lat1, lon1, azi1, caps=Caps.ALL, **name):
1100 '''Set up a L{GeodesicLineExact} to compute several points
1101 on a single geodesic.
1103 @arg lat1: Latitude of the first point (C{degrees}).
1104 @arg lon1: Longitude of the first point (C{degrees}).
1105 @arg azi1: Azimuth at the first point (compass C{degrees}).
1106 @kwarg caps: Bit-or'ed combination of L{Caps} values specifying
1107 the capabilities the L{GeodesicLineExact} instance
1108 should possess, i.e., which quantities can be
1109 returnedby calls to L{GeodesicLineExact.Position}
1110 and L{GeodesicLineExact.ArcPosition}.
1111 @kwarg name: Optional C{B{name}=NN} (C{str}).
1113 @return: A L{GeodesicLineExact} instance.
1115 @note: If the point is at a pole, the azimuth is defined by keeping
1116 B{C{lon1}} fixed, writing C{B{lat1} = ±(90 − ε)}, and taking
1117 the limit C{ε → 0+}.
1119 @see: C++ U{GeodesicExact.Line
1120 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>}
1121 and Python U{Geodesic.Line<https://GeographicLib.SourceForge.io/Python/doc/code.html>}.
1122 '''
1123 return GeodesicLineExact(self, lat1, lon1, azi1, caps=caps, **name)._GenSet(self._debug)
1125 @Property_RO
1126 def n(self):
1127 '''Get the C{ellipsoid}'s I{3rd flattening} (C{scalar}), M{f / (2 - f) == (a - b) / (a + b)}.
1128 '''
1129 return self.ellipsoid.n
1131 @Property_RO
1132 def _n_0_1(self):
1133 '''(INTERNAL) Cached once.
1134 '''
1135 return fabs(self.n) > _0_1
1137 @Property_RO
1138 def _n6PI(self):
1139 '''(INTERNAL) Cached once.
1140 '''
1141 return fabs(self.n) * _6_0 * PI
1143 def _Newton6(self, salp1, calp1, p):
1144 '''(INTERNAL) Split off from C{_GDictInverse} to reduce complexity/length.
1146 @return: 6-Tuple C{(sig12, salp1, calp1, salp2, calp2, domg12)}
1147 and C{p.iter} and C{p.trip} updated.
1148 '''
1149 _abs = fabs
1150 # This is a straightforward solution of f(alp1) = lambda12(alp1) -
1151 # lam12 = 0 with one wrinkle. f(alp) has exactly one root in the
1152 # interval (0, PI) and its derivative is positive at the root.
1153 # Thus f(alp) is positive for alp > alp1 and negative for alp < alp1.
1154 # During the course of the iteration, a range (alp1a, alp1b) is
1155 # maintained which brackets the root and with each evaluation of
1156 # f(alp) the range is shrunk, if possible. Newton's method is
1157 # restarted whenever the derivative of f is negative (because the
1158 # new value of alp1 is then further from the solution) or if the
1159 # new estimate of alp1 lies outside (0,PI); in this case, the new
1160 # starting guess is taken to be (alp1a + alp1b) / 2.
1161 salp1a = salp1b = _TINY
1162 calp1a, calp1b = _1_0, _N_1_0
1163 MAXIT1, TOL0 = _MAXIT1, _TOL0
1164 HALF, TOLb = _0_5, _TOLb
1165 tripb, TOLv = False, TOL0
1166 for i in range(_MAXIT2):
1167 # 1/4 meridian = 10e6 meter and random input,
1168 # estimated max error in nm (nano meter, by
1169 # checking Inverse problem by Direct).
1170 #
1171 # max iterations
1172 # log2(b/a) error mean sd
1173 # -7 387 5.33 3.68
1174 # -6 345 5.19 3.43
1175 # -5 269 5.00 3.05
1176 # -4 210 4.76 2.44
1177 # -3 115 4.55 1.87
1178 # -2 69 4.35 1.38
1179 # -1 36 4.05 1.03
1180 # 0 15 0.01 0.13
1181 # 1 25 5.10 1.53
1182 # 2 96 5.61 2.09
1183 # 3 318 6.02 2.74
1184 # 4 985 6.24 3.22
1185 # 5 2352 6.32 3.44
1186 # 6 6008 6.30 3.45
1187 # 7 19024 6.19 3.30
1188 v, sig12, salp2, calp2, \
1189 domg12, dv = self._Lambda6(salp1, calp1, i < MAXIT1, p)
1191 # 2 * _TOL0 is approximately 1 ulp [0, PI]
1192 # reversed test to allow escape with NaNs
1193 if tripb or _abs(v) < TOLv:
1194 break
1195 # update bracketing values
1196 if v > 0 and (i > MAXIT1 or (calp1 / salp1) > (calp1b / salp1b)):
1197 salp1b, calp1b = salp1, calp1
1198 elif v < 0 and (i > MAXIT1 or (calp1 / salp1) < (calp1a / salp1a)):
1199 salp1a, calp1a = salp1, calp1
1201 if i < MAXIT1 and dv > 0:
1202 dalp1 = -v / dv
1203 if _abs(dalp1) < PI:
1204 s, c = _sincos2(dalp1)
1205 # nalp1 = alp1 + dalp1
1206 s, c = _sincos12(-s, c, salp1, calp1)
1207 if s > 0:
1208 salp1, calp1 = _norm2(s, c)
1209 # in some regimes we don't get quadratic convergence
1210 # because slope -> 0. So use convergence conditions
1211 # based on epsilon instead of sqrt(epsilon)
1212 TOLv = TOL0 if _abs(v) > _TOL016 else _TOL08
1213 continue
1214 TOLv = TOL0
1215 # Either dv was not positive or updated value was outside
1216 # legal range. Use the midpoint of the bracket as the next
1217 # estimate. This mechanism is not needed for the WGS84
1218 # ellipsoid, but it does catch problems with more eccentric
1219 # ellipsoids. Its efficacy is such for the WGS84 test set
1220 # with the starting guess set to alp1 = 90 deg: the WGS84
1221 # test set: mean = 5.21, stdev = 3.93, max = 24 and WGS84
1222 # with random input: mean = 4.74, stdev = 0.99
1223 salp1, calp1 = _norm2((salp1a + salp1b) * HALF,
1224 (calp1a + calp1b) * HALF)
1225 tripb = fsum1f_(calp1a, -calp1, _abs(salp1a - salp1)) < TOLb or \
1226 fsum1f_(calp1b, -calp1, _abs(salp1b - salp1)) < TOLb
1227 else:
1228 raise GeodesicError(Fmt.no_convergence(v, TOLv), txt=repr(self)) # self.toRepr()
1230 p.set_(iter=i, trip=tripb) # like .geodsolve._GDictInvoke: iter NOT iteration!
1231 return sig12, salp1, calp1, salp2, calp2, domg12
1233 Polygon = Area # for C{geographiclib} compatibility
1235 def toStr(self, **prec_sep_name): # PYCHOK signature
1236 '''Return this C{GeodesicExact} as string.
1238 @see: L{Ellipsoid.toStr<pygeodesy.ellipsoids.Ellipsoid.toStr>}
1239 for further details.
1241 @return: C{GeodesicExact} (C{str}).
1242 '''
1243 t = GeodesicExact.caps, GeodesicExact.ellipsoid
1244 return self._instr(props=t, C4order=self.C4order, **prec_sep_name)
1247class GeodesicLineExact(_GeodesicLineExact):
1248 '''A pure Python version of I{Karney}'s C++ class U{GeodesicLineExact
1249 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicLineExact.html>},
1250 modeled after I{Karney}'s Python class U{geodesicline.GeodesicLine<https://GitHub.com/
1251 geographiclib/geographiclib-python>}.
1252 '''
1254 def __init__(self, geodesic, lat1, lon1, azi1, caps=Caps.STANDARD, **name):
1255 '''New L{GeodesicLineExact} instance, allowing points to be found along
1256 a geodesic starting at C{(B{lat1}, B{lon1})} with azimuth B{C{azi1}}.
1258 @arg geodesic: The geodesic to use (L{GeodesicExact}).
1259 @arg lat1: Latitude of the first point (C{degrees}).
1260 @arg lon1: Longitude of the first point (C{degrees}).
1261 @arg azi1: Azimuth at the first points (compass C{degrees}).
1262 @kwarg caps: Bit-or'ed combination of L{Caps} values specifying
1263 the capabilities the L{GeodesicLineExact} instance
1264 should possess, i.e., which quantities can be
1265 returned by calls to L{GeodesicLineExact.Position}
1266 and L{GeodesicLineExact.ArcPosition}.
1267 @kwarg name: Optional C{B{name}=NN} (C{str}).
1269 @raise TypeError: Invalid B{C{geodesic}}.
1270 '''
1271 _xinstanceof(GeodesicExact, geodesic=geodesic)
1272 if (caps & Caps.LINE_OFF): # copy to avoid updates
1273 geodesic = geodesic.copy(deep=False, name=_UNDER_(NN, geodesic.name))
1274# _update_all(geodesic)
1275 _GeodesicLineExact.__init__(self, geodesic, lat1, lon1, azi1, caps, **name)
1278def _Astroid(x, y):
1279 '''(INTERNAL) Solve M{k^4 + 2 * k^3 - (x^2 + y^2 - 1)
1280 * k^2 - (2 * k + 1) * y^2 = 0} for positive root k.
1281 '''
1282 p = x**2
1283 q = y**2
1284 r = fsumf_(_1_0, q, p, _N_2_0)
1285 if r > 0 or q:
1286 # avoid possible division by zero when r = 0
1287 # by multiplying s and t by r^3 and r, resp.
1288 S = p * q / _4_0 # S = r^3 * s
1289 if r:
1290 r = r / _6_0 # /= chokes PyChecker
1291 r3 = r**3
1292 T3 = r3 + S
1293 # discriminant of the quadratic equation for T3 is
1294 # zero on the evolute curve p^(1/3) + q^(1/3) = 1
1295 d = (r3 + T3) * S
1296 if d < 0:
1297 # T is complex, but u is defined for a real result
1298 a = atan2(sqrt(-d), -T3) / _3_0
1299 # There are 3 possible cube roots, choose the one which
1300 # avoids cancellation. Note d < 0 implies that r < 0.
1301 u = (cos(a) * _2_0 + _1_0) * r
1302 else:
1303 # pick the sign on the sqrt to maximize abs(T3) to
1304 # minimize loss of precision due to cancellation.
1305 if d:
1306 T3 += _copysign(sqrt(d), T3) # T3 = (r * t)^3
1307 # _cbrt always returns the real root, _cbrt(-8) = -2
1308 u = _cbrt(T3) # T = r * t
1309 if u: # T can be zero; but then r2 / T -> 0
1310 u += r**2 / u
1311 u += r
1312 elif S: # d == T3**2 == S**2: sqrt(d) == abs(S) == abs(T3)
1313 u = _cbrt(S * _2_0) # == T3 + _copysign(abs(S), T3)
1314 else:
1315 u = _0_0
1316 v = _hypot(u, y) # sqrt(u**2 + q)
1317 # avoid loss of accuracy when u < 0
1318 u = (q / (v - u)) if u < 0 else (v + u)
1319 w = (u - q) / (v + v) # positive?
1320 # rearrange expression for k to avoid loss of accuracy due to
1321 # subtraction, division by 0 impossible because u > 0, w >= 0
1322 k = u / (sqrt(w**2 + u) + w) # guaranteed positive
1324 else: # q == 0 && r <= 0
1325 # y = 0 with |x| <= 1. Handle this case directly, for
1326 # y small, positive root is k = abs(y) / sqrt(1 - x^2)
1327 k = _0_0
1329 return k
1332def _C4coeffs(nC4): # in .geodesicx.__main__
1333 '''(INTERNAL) Get the C{C4_24}, C{_27} or C{_30} series coefficients.
1334 '''
1335 try: # from pygeodesy.geodesicx._C4_xx import _coeffs_xx as _coeffs
1336 _C4_xx = _DOT_(_MODS.geodesicx.__name__, _UNDER_('_C4', nC4))
1337 _coeffs = _MODS.getattr(_C4_xx, _UNDER_('_coeffs', nC4))
1338 except (AttributeError, ImportError, TypeError) as x:
1339 raise GeodesicError(nC4=nC4, cause=x)
1340 n = _xnC4(nC4=nC4)
1341 if len(_coeffs) != n: # double check
1342 raise GeodesicError(_coeffs=len(_coeffs), _xnC4=n, nC4=nC4)
1343 return _coeffs
1346__all__ += _ALL_DOCS(GeodesicExact, GeodesicLineExact)
1348# **) MIT License
1349#
1350# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved.
1351#
1352# Permission is hereby granted, free of charge, to any person obtaining a
1353# copy of this software and associated documentation files (the "Software"),
1354# to deal in the Software without restriction, including without limitation
1355# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1356# and/or sell copies of the Software, and to permit persons to whom the
1357# Software is furnished to do so, subject to the following conditions:
1358#
1359# The above copyright notice and this permission notice shall be included
1360# in all copies or substantial portions of the Software.
1361#
1362# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1363# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1364# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1365# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1366# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1367# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1368# OTHER DEALINGS IN THE SOFTWARE.