Coverage for pygeodesy/formy.py: 99%
407 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-08-07 07:28 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2023-08-07 07:28 -0400
2# -*- coding: utf-8 -*-
4u'''Formulary of basic geodesy functions and approximations.
5'''
6# make sure int/int division yields float quotient, see .basics
7from __future__ import division as _; del _ # PYCHOK semicolon
9# from pygeodesy.basics import isscalar # from .fsums
10from pygeodesy.constants import EPS, EPS0, EPS1, PI, PI2, PI3, PI_2, R_M, \
11 _umod_PI2, float0_, isnon0, remainder, \
12 _0_0, _0_125, _0_25, _0_5, _1_0, _2_0, \
13 _4_0, _32_0, _90_0, _180_0, _360_0
14from pygeodesy.datums import Datum, Ellipsoid, _ellipsoidal_datum, \
15 _mean_radius, _spherical_datum, _WGS84
16# from pygeodesy.ellipsoids import Ellipsoid # from .datums
17from pygeodesy.errors import IntersectionError, LimitError, limiterrors, \
18 _TypeError, _ValueError, \
19 _xError, _xkwds, _xkwds_pop
20from pygeodesy.fmath import euclid, hypot, hypot2, sqrt0
21from pygeodesy.fsums import fsumf_, isscalar
22from pygeodesy.interns import NN, _delta_, _distant_, _SPACE_, _too_
23from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS
24from pygeodesy.named import _NamedTuple, _xnamed, Fmt, unstr
25from pygeodesy.namedTuples import Bearing2Tuple, Distance4Tuple, \
26 Intersection3Tuple, LatLon2Tuple, \
27 PhiLam2Tuple, Vector3Tuple
28# from pygeodesy.streprs import Fmt, unstr # from .named
29from pygeodesy.units import Bearing, Degrees_, Distance, Distance_, Height, \
30 Lam_, Lat, Lon, Meter_, Phi_, Radians, Radians_, \
31 Radius, Radius_, Scalar, _100km
32from pygeodesy.utily import acos1, atan2b, atan2d, degrees2m, m2degrees, \
33 tan_2, sincos2, sincos2_, sincos2d_, _Wrap
35from contextlib import contextmanager
36from math import atan, atan2, cos, degrees, fabs, radians, sin, sqrt # pow
38__all__ = _ALL_LAZY.formy
39__version__ = '23.06.08'
41_D2_R2 = (PI / _180_0)**2 # degrees- to radians-squared
42_EWGS84 = _WGS84.ellipsoid
43_ratio_ = 'ratio'
44_xline_ = 'xline'
47def _anti2(a, b, n_2, n, n2):
48 '''(INTERNAL) Helper for C{antipode} and C{antipode_}.
49 '''
50 r = remainder(a, n) if fabs(a) > n_2 else a
51 if r == a:
52 r = -r
53 b += n
54 if fabs(b) > n:
55 b = remainder(b, n2)
56 return float0_(r, b)
59def antipode(lat, lon, name=NN):
60 '''Return the antipode, the point diametrically opposite
61 to a given point in C{degrees}.
63 @arg lat: Latitude (C{degrees}).
64 @arg lon: Longitude (C{degrees}).
65 @kwarg name: Optional name (C{str}).
67 @return: A L{LatLon2Tuple}C{(lat, lon)}.
69 @see: Functions L{antipode_} and L{normal} and U{Geosphere
70 <https://CRAN.R-Project.org/web/packages/geosphere/geosphere.pdf>}.
71 '''
72 return LatLon2Tuple(*_anti2(lat, lon, _90_0, _180_0, _360_0), name=name)
75def antipode_(phi, lam, name=NN):
76 '''Return the antipode, the point diametrically opposite
77 to a given point in C{radians}.
79 @arg phi: Latitude (C{radians}).
80 @arg lam: Longitude (C{radians}).
81 @kwarg name: Optional name (C{str}).
83 @return: A L{PhiLam2Tuple}C{(phi, lam)}.
85 @see: Functions L{antipode} and L{normal_} and U{Geosphere
86 <https://CRAN.R-Project.org/web/packages/geosphere/geosphere.pdf>}.
87 '''
88 return PhiLam2Tuple(*_anti2(phi, lam, PI_2, PI, PI2), name=name)
91def bearing(lat1, lon1, lat2, lon2, **final_wrap):
92 '''Compute the initial or final bearing (forward or reverse
93 azimuth) between a (spherical) start and end point.
95 @arg lat1: Start latitude (C{degrees}).
96 @arg lon1: Start longitude (C{degrees}).
97 @arg lat2: End latitude (C{degrees}).
98 @arg lon2: End longitude (C{degrees}).
99 @kwarg final_wrap: Optional keyword arguments for function
100 L{pygeodesy.bearing_}.
102 @return: Initial or final bearing (compass C{degrees360}) or
103 zero if start and end point coincide.
104 '''
105 r = bearing_(Phi_(lat1=lat1), Lam_(lon1=lon1),
106 Phi_(lat2=lat2), Lam_(lon2=lon2), **final_wrap)
107 return degrees(r)
110def bearing_(phi1, lam1, phi2, lam2, final=False, wrap=False):
111 '''Compute the initial or final bearing (forward or reverse azimuth)
112 between a (spherical) start and end point.
114 @arg phi1: Start latitude (C{radians}).
115 @arg lam1: Start longitude (C{radians}).
116 @arg phi2: End latitude (C{radians}).
117 @arg lam2: End longitude (C{radians}).
118 @kwarg final: Return final bearing if C{True}, initial otherwise (C{bool}).
119 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll B{C{phi2}} and
120 B{C{lam2}} (C{bool}).
122 @return: Initial or final bearing (compass C{radiansPI2}) or zero if start
123 and end point coincide.
125 @see: U{Bearing<https://www.Movable-Type.co.UK/scripts/latlong.html>}, U{Course
126 between two points<https://www.EdWilliams.org/avform147.htm#Crs>} and
127 U{Bearing Between Two Points<https://web.Archive.org/web/20020630205931/
128 https://MathForum.org/library/drmath/view/55417.html>}.
129 '''
130 db, phi2, lam2 = _Wrap.philam3(lam1, phi2, lam2, wrap)
131 if final: # swap plus PI
132 phi1, lam1, phi2, lam2, db = phi2, lam2, phi1, lam1, -db
133 r = PI3
134 else:
135 r = PI2
136 sa1, ca1, sa2, ca2, sdb, cdb = sincos2_(phi1, phi2, db)
138 x = ca1 * sa2 - sa1 * ca2 * cdb
139 y = sdb * ca2
140 return _umod_PI2(atan2(y, x) + r) # .utily.wrapPI2
143def _bearingTo2(p1, p2, wrap=False): # for points.ispolar, sphericalTrigonometry.areaOf
144 '''(INTERNAL) Compute initial and final bearing.
145 '''
146 try: # for LatLon_ and ellipsoidal LatLon
147 return p1.bearingTo2(p2, wrap=wrap)
148 except AttributeError:
149 pass
150 # XXX spherical version, OK for ellipsoidal ispolar?
151 a1, b1 = p1.philam
152 a2, b2 = p2.philam
153 return Bearing2Tuple(degrees(bearing_(a1, b1, a2, b2, final=False, wrap=wrap)),
154 degrees(bearing_(a1, b1, a2, b2, final=True, wrap=wrap)),
155 name=_bearingTo2.__name__)
158def compassAngle(lat1, lon1, lat2, lon2, adjust=True, wrap=False):
159 '''Return the angle from North for the direction vector M{(lon2 - lon1,
160 lat2 - lat1)} between two points.
162 Suitable only for short, not near-polar vectors up to a few hundred
163 Km or Miles. Use function L{pygeodesy.bearing} for longer vectors.
165 @arg lat1: From latitude (C{degrees}).
166 @arg lon1: From longitude (C{degrees}).
167 @arg lat2: To latitude (C{degrees}).
168 @arg lon2: To longitude (C{degrees}).
169 @kwarg adjust: Adjust the longitudinal delta by the cosine of the
170 mean latitude (C{bool}).
171 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll B{C{lat2}}
172 and B{C{lon2}} (C{bool}).
174 @return: Compass angle from North (C{degrees360}).
176 @note: Courtesy of Martin Schultz.
178 @see: U{Local, flat earth approximation
179 <https://www.EdWilliams.org/avform.htm#flat>}.
180 '''
181 d_lon, lat2, lon2 = _Wrap.latlon3(lon1, lat2, lon2, wrap)
182 if adjust: # scale delta lon
183 d_lon *= _scale_deg(lat1, lat2)
184 return atan2b(d_lon, lat2 - lat1)
187def cosineAndoyerLambert(lat1, lon1, lat2, lon2, datum=_WGS84, wrap=False):
188 '''Compute the distance between two (ellipsoidal) points using the
189 U{Andoyer-Lambert correction<https://NavLib.net/wp-content/uploads/2013/10/
190 admiralty-manual-of-navigation-vol-1-1964-english501c.pdf>} of the U{Law of
191 Cosines<https://www.Movable-Type.co.UK/scripts/latlong.html#cosine-law>} formula.
193 @arg lat1: Start latitude (C{degrees}).
194 @arg lon1: Start longitude (C{degrees}).
195 @arg lat2: End latitude (C{degrees}).
196 @arg lon2: End longitude (C{degrees}).
197 @kwarg datum: Datum (L{Datum}) or ellipsoid (L{Ellipsoid},
198 L{Ellipsoid2} or L{a_f2Tuple}) to use.
199 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll
200 B{C{lat2}} and B{C{lon2}} (C{bool}).
202 @return: Distance (C{meter}, same units as the B{C{datum}}'s
203 ellipsoid axes or C{radians} if B{C{datum}} is C{None}).
205 @raise TypeError: Invalid B{C{datum}}.
207 @see: Functions L{cosineAndoyerLambert_}, L{cosineForsytheAndoyerLambert},
208 L{cosineLaw}, L{equirectangular}, L{euclidean}, L{flatLocal}/L{hubeny},
209 L{flatPolar}, L{haversine}, L{thomas} and L{vincentys} and method
210 L{Ellipsoid.distance2}.
211 '''
212 return _dE(cosineAndoyerLambert_, datum, wrap, lat1, lon1, lat2, lon2)
215def cosineAndoyerLambert_(phi2, phi1, lam21, datum=_WGS84):
216 '''Compute the I{angular} distance between two (ellipsoidal) points using the
217 U{Andoyer-Lambert correction<https://NavLib.net/wp-content/uploads/2013/10/
218 admiralty-manual-of-navigation-vol-1-1964-english501c.pdf>} of the U{Law of
219 Cosines<https://www.Movable-Type.co.UK/scripts/latlong.html#cosine-law>} formula.
221 @arg phi2: End latitude (C{radians}).
222 @arg phi1: Start latitude (C{radians}).
223 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).
224 @kwarg datum: Datum (L{Datum}) or ellipsoid (L{Ellipsoid},
225 L{Ellipsoid2} or L{a_f2Tuple}) to use.
227 @return: Angular distance (C{radians}).
229 @raise TypeError: Invalid B{C{datum}}.
231 @see: Functions L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert_},
232 L{cosineLaw_}, L{equirectangular_}, L{euclidean_}, L{flatLocal_}/L{hubeny_},
233 L{flatPolar_}, L{haversine_}, L{thomas_} and L{vincentys_} and U{Geodesy-PHP
234 <https://GitHub.com/jtejido/geodesy-php/blob/master/src/Geodesy/Distance/
235 AndoyerLambert.php>}.
236 '''
237 s2, c2, s1, c1, r, c21 = _sincosa6(phi2, phi1, lam21)
238 if isnon0(c1) and isnon0(c2):
239 E = _ellipsoidal(datum, cosineAndoyerLambert_)
240 if E.f: # ellipsoidal
241 r2 = atan2(E.b_a * s2, c2)
242 r1 = atan2(E.b_a * s1, c1)
243 s2, c2, s1, c1 = sincos2_(r2, r1)
244 r = acos1(s1 * s2 + c1 * c2 * c21)
245 if r:
246 sr, _, sr_2, cr_2 = sincos2_(r, r * _0_5)
247 if isnon0(sr_2) and isnon0(cr_2):
248 s = (sr + r) * ((s1 - s2) / sr_2)**2
249 c = (sr - r) * ((s1 + s2) / cr_2)**2
250 r += (c - s) * E.f * _0_125
251 return r
254def cosineForsytheAndoyerLambert(lat1, lon1, lat2, lon2, datum=_WGS84, wrap=False):
255 '''Compute the distance between two (ellipsoidal) points using the
256 U{Forsythe-Andoyer-Lambert correction<https://www2.UNB.Ca/gge/Pubs/TR77.pdf>} of
257 the U{Law of Cosines<https://www.Movable-Type.co.UK/scripts/latlong.html#cosine-law>}
258 formula.
260 @arg lat1: Start latitude (C{degrees}).
261 @arg lon1: Start longitude (C{degrees}).
262 @arg lat2: End latitude (C{degrees}).
263 @arg lon2: End longitude (C{degrees}).
264 @kwarg datum: Datum (L{Datum}) or ellipsoid (L{Ellipsoid},
265 L{Ellipsoid2} or L{a_f2Tuple}) to use.
266 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll
267 B{C{lat2}} and B{C{lon2}} (C{bool}).
269 @return: Distance (C{meter}, same units as the B{C{datum}}'s
270 ellipsoid axes or C{radians} if B{C{datum}} is C{None}).
272 @raise TypeError: Invalid B{C{datum}}.
274 @see: Functions L{cosineForsytheAndoyerLambert_}, L{cosineAndoyerLambert},
275 L{cosineLaw}, L{equirectangular}, L{euclidean}, L{flatLocal}/L{hubeny},
276 L{flatPolar}, L{haversine}, L{thomas} and L{vincentys} and method
277 L{Ellipsoid.distance2}.
278 '''
279 return _dE(cosineForsytheAndoyerLambert_, datum, wrap, lat1, lon1, lat2, lon2)
282def cosineForsytheAndoyerLambert_(phi2, phi1, lam21, datum=_WGS84):
283 '''Compute the I{angular} distance between two (ellipsoidal) points using the
284 U{Forsythe-Andoyer-Lambert correction<https://www2.UNB.Ca/gge/Pubs/TR77.pdf>} of
285 the U{Law of Cosines<https://www.Movable-Type.co.UK/scripts/latlong.html#cosine-law>}
286 formula.
288 @arg phi2: End latitude (C{radians}).
289 @arg phi1: Start latitude (C{radians}).
290 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).
291 @kwarg datum: Datum (L{Datum}) or ellipsoid to use (L{Ellipsoid},
292 L{Ellipsoid2} or L{a_f2Tuple}).
294 @return: Angular distance (C{radians}).
296 @raise TypeError: Invalid B{C{datum}}.
298 @see: Functions L{cosineForsytheAndoyerLambert}, L{cosineAndoyerLambert_},
299 L{cosineLaw_}, L{equirectangular_}, L{euclidean_}, L{flatLocal_}/L{hubeny_},
300 L{flatPolar_}, L{haversine_}, L{thomas_} and L{vincentys_} and U{Geodesy-PHP
301 <https://GitHub.com/jtejido/geodesy-php/blob/master/src/Geodesy/
302 Distance/ForsytheCorrection.php>}.
303 '''
304 s2, c2, s1, c1, r, _ = _sincosa6(phi2, phi1, lam21)
305 if r and isnon0(c1) and isnon0(c2):
306 E = _ellipsoidal(datum, cosineForsytheAndoyerLambert_)
307 if E.f: # ellipsoidal
308 sr, cr, s2r, _ = sincos2_(r, r * 2)
309 if isnon0(sr) and fabs(cr) < EPS1:
310 s = (s1 + s2)**2 / (1 + cr)
311 t = (s1 - s2)**2 / (1 - cr)
312 x = s + t
313 y = s - t
315 s = 8 * r**2 / sr
316 a = 64 * r + s * cr * 2 # 16 * r**2 / tan(r)
317 d = 48 * sr + s # 8 * r**2 / tan(r)
318 b = -2 * d
319 e = 30 * s2r
320 c = fsumf_(30 * r, e * _0_5, s * cr) # 8 * r**2 / tan(r)
322 t = fsumf_( a * x, b * y, -c * x**2, d * x * y, e * y**2)
323 r += fsumf_(-r * x, 3 * y * sr, t * E.f / _32_0) * E.f * _0_25
324 return r
327def cosineLaw(lat1, lon1, lat2, lon2, radius=R_M, wrap=False):
328 '''Compute the distance between two points using the U{spherical Law of
329 Cosines<https://www.Movable-Type.co.UK/scripts/latlong.html#cosine-law>}
330 formula.
332 @arg lat1: Start latitude (C{degrees}).
333 @arg lon1: Start longitude (C{degrees}).
334 @arg lat2: End latitude (C{degrees}).
335 @arg lon2: End longitude (C{degrees}).
336 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum})
337 or ellipsoid (L{Ellipsoid}, L{Ellipsoid2} or
338 L{a_f2Tuple}) to use.
339 @kwarg wrap: If C{True}, wrap or I{normalize} and B{C{lat2}}
340 and B{C{lon2}} (C{bool}).
342 @return: Distance (C{meter}, same units as B{C{radius}} or the
343 ellipsoid or datum axes).
345 @raise TypeError: Invalid B{C{radius}}.
347 @see: Functions L{cosineLaw_}, L{cosineAndoyerLambert},
348 L{cosineForsytheAndoyerLambert}, L{equirectangular}, L{euclidean},
349 L{flatLocal}/L{hubeny}, L{flatPolar}, L{haversine}, L{thomas} and
350 L{vincentys} and method L{Ellipsoid.distance2}.
352 @note: See note at function L{vincentys_}.
353 '''
354 return _dS(cosineLaw_, radius, wrap, lat1, lon1, lat2, lon2)
357def cosineLaw_(phi2, phi1, lam21):
358 '''Compute the I{angular} distance between two points using the U{spherical
359 Law of Cosines<https://www.Movable-Type.co.UK/scripts/latlong.html#cosine-law>}
360 formula.
362 @arg phi2: End latitude (C{radians}).
363 @arg phi1: Start latitude (C{radians}).
364 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).
366 @return: Angular distance (C{radians}).
368 @see: Functions L{cosineLaw}, L{cosineAndoyerLambert_},
369 L{cosineForsytheAndoyerLambert_}, L{equirectangular_},
370 L{euclidean_}, L{flatLocal_}/L{hubeny_}, L{flatPolar_},
371 L{haversine_}, L{thomas_} and L{vincentys_}.
373 @note: See note at function L{vincentys_}.
374 '''
375 return _sincosa6(phi2, phi1, lam21)[4]
378def _d3(wrap, lat1, lon1, lat2, lon2):
379 '''(INTERNAL) Helper for _dE, _dS and _eA.
380 '''
381 if wrap:
382 d_lon, lat2, _ = _Wrap.latlon3(lon1, lat2, lon2, wrap)
383 return radians(lat2), Phi_(lat1=lat1), radians(d_lon)
384 else: # for backward compaibility
385 return Phi_(lat2=lat2), Phi_(lat1=lat1), Phi_(d_lon=lon2 - lon1)
388def _dE(func_, earth, *wrap_lls):
389 '''(INTERNAL) Helper for ellipsoidal distances.
390 '''
391 E = _ellipsoidal(earth, func_)
392 r = func_(*_d3(*wrap_lls), datum=E)
393 return r * E.a
396def _dS(func_, radius, *wrap_lls, **adjust):
397 '''(INTERNAL) Helper for spherical distances.
398 '''
399 r = func_(*_d3(*wrap_lls), **adjust)
400 if radius is not R_M:
401 _, lat1, _, lat2, _ = wrap_lls
402 radius = _mean_radius(radius, lat1, lat2)
403 return r * radius
406def _eA(excess_, radius, *wrap_lls):
407 '''(INTERNAL) Helper for spherical excess or area.
408 '''
409 r = excess_(*_d3(*wrap_lls))
410 if radius:
411 _, lat1, _, lat2, _ = wrap_lls
412 r *= _mean_radius(radius, lat1, lat2)**2
413 return r
416def _ellipsoidal(earth, where):
417 '''(INTERNAL) Helper for distances.
418 '''
419 return _EWGS84 if earth in (_WGS84, _EWGS84) else (
420 earth if isinstance(earth, Ellipsoid) else
421 (earth if isinstance(earth, Datum) else # PYCHOK indent
422 _ellipsoidal_datum(earth, name=where.__name__)).ellipsoid)
425def equirectangular(lat1, lon1, lat2, lon2, radius=R_M, **adjust_limit_wrap):
426 '''Compute the distance between two points using
427 the U{Equirectangular Approximation / Projection
428 <https://www.Movable-Type.co.UK/scripts/latlong.html#equirectangular>}.
430 @arg lat1: Start latitude (C{degrees}).
431 @arg lon1: Start longitude (C{degrees}).
432 @arg lat2: End latitude (C{degrees}).
433 @arg lon2: End longitude (C{degrees}).
434 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum})
435 or ellipsoid (L{Ellipsoid}, L{Ellipsoid2} or
436 L{a_f2Tuple}).
437 @kwarg adjust_limit_wrap: Optional keyword arguments for
438 function L{equirectangular_}.
440 @return: Distance (C{meter}, same units as B{C{radius}} or
441 the ellipsoid or datum axes).
443 @raise TypeError: Invalid B{C{radius}}.
445 @see: Function L{equirectangular_} for more details, the
446 available B{C{options}}, errors, restrictions and other,
447 approximate or accurate distance functions.
448 '''
449 d = sqrt(equirectangular_(Lat(lat1=lat1), Lon(lon1=lon1),
450 Lat(lat2=lat2), Lon(lon2=lon2),
451 **adjust_limit_wrap).distance2) # PYCHOK 4 vs 2-3
452 return degrees2m(d, radius=_mean_radius(radius, lat1, lat2))
455def _equirectangular(lat1, lon1, lat2, lon2, **adjust_limit_wrap):
456 '''(INTERNAL) Helper for the L{frechet._FrecherMeterRadians}
457 and L{hausdorff._HausdorffMeterRedians} classes.
458 '''
459 return equirectangular_(lat1, lon1, lat2, lon2, **adjust_limit_wrap).distance2 * _D2_R2
462def equirectangular_(lat1, lon1, lat2, lon2, adjust=True, limit=45, wrap=False):
463 '''Compute the distance between two points using the U{Equirectangular
464 Approximation / Projection
465 <https://www.Movable-Type.co.UK/scripts/latlong.html#equirectangular>}.
467 This approximation is valid for short distance of several hundred Km
468 or Miles, see the B{C{limit}} keyword argument and L{LimitError}.
470 @arg lat1: Start latitude (C{degrees}).
471 @arg lon1: Start longitude (C{degrees}).
472 @arg lat2: End latitude (C{degrees}).
473 @arg lon2: End longitude (C{degrees}).
474 @kwarg adjust: Adjust the wrapped, unrolled longitudinal delta
475 by the cosine of the mean latitude (C{bool}).
476 @kwarg limit: Optional limit for lat- and longitudinal deltas
477 (C{degrees}) or C{None} or C{0} for unlimited.
478 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll B{C{lat2}}
479 and B{C{lon2}} (C{bool}).
481 @return: A L{Distance4Tuple}C{(distance2, delta_lat, delta_lon,
482 unroll_lon2)} in C{degrees squared}.
484 @raise LimitError: If the lat- and/or longitudinal delta exceeds the
485 B{C{-limit..limit}} range and L{pygeodesy.limiterrors}
486 set to C{True}.
488 @see: U{Local, flat earth approximation
489 <https://www.EdWilliams.org/avform.htm#flat>}, functions
490 L{equirectangular}, L{cosineAndoyerLambert},
491 L{cosineForsytheAndoyerLambert}, L{cosineLaw}, L{euclidean},
492 L{flatLocal}/L{hubeny}, L{flatPolar}, L{haversine}, L{thomas}
493 and L{vincentys} and methods L{Ellipsoid.distance2},
494 C{LatLon.distanceTo*} and C{LatLon.equirectangularTo}.
495 '''
496 d_lon, lat2, ulon2 = _Wrap.latlon3(lon1, lat2, lon2, wrap)
497 d_lat = lat2 - lat1
499 if limit and limit > 0 and limiterrors():
500 d = max(fabs(d_lat), fabs(d_lon))
501 if d > limit:
502 t = _SPACE_(_delta_, Fmt.PAREN_g(d), Fmt.exceeds_limit(limit))
503 s = unstr(equirectangular_, lat1, lon1, lat2, lon2,
504 limit=limit, wrap=wrap)
505 raise LimitError(s, txt=t)
507 if adjust: # scale delta lon
508 d_lon *= _scale_deg(lat1, lat2)
510 d2 = hypot2(d_lat, d_lon) # degrees squared!
511 return Distance4Tuple(d2, d_lat, d_lon, ulon2 - lon2)
514def euclidean(lat1, lon1, lat2, lon2, radius=R_M, adjust=True, wrap=False):
515 '''Approximate the C{Euclidean} distance between two (spherical) points.
517 @arg lat1: Start latitude (C{degrees}).
518 @arg lon1: Start longitude (C{degrees}).
519 @arg lat2: End latitude (C{degrees}).
520 @arg lon2: End longitude (C{degrees}).
521 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum})
522 or ellipsoid (L{Ellipsoid}, L{Ellipsoid2} or
523 L{a_f2Tuple}) to use.
524 @kwarg adjust: Adjust the longitudinal delta by the cosine of
525 the mean latitude (C{bool}).
526 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll B{C{lat2}}
527 and B{C{lon2}} (C{bool}).
529 @return: Distance (C{meter}, same units as B{C{radius}} or the
530 ellipsoid or datum axes).
532 @raise TypeError: Invalid B{C{radius}}.
534 @see: U{Distance between two (spherical) points
535 <https://www.EdWilliams.org/avform.htm#Dist>}, functions L{euclid},
536 L{euclidean_}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},
537 L{cosineLaw}, L{equirectangular}, L{flatLocal}/L{hubeny}, L{flatPolar},
538 L{haversine}, L{thomas} and L{vincentys} and methods L{Ellipsoid.distance2},
539 C{LatLon.distanceTo*} and C{LatLon.equirectangularTo}.
540 '''
541 return _dS(euclidean_, radius, wrap, lat1, lon1, lat2, lon2, adjust=adjust)
544def euclidean_(phi2, phi1, lam21, adjust=True):
545 '''Approximate the I{angular} C{Euclidean} distance between two
546 (spherical) points.
548 @arg phi2: End latitude (C{radians}).
549 @arg phi1: Start latitude (C{radians}).
550 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).
551 @kwarg adjust: Adjust the longitudinal delta by the cosine
552 of the mean latitude (C{bool}).
554 @return: Angular distance (C{radians}).
556 @see: Functions L{euclid}, L{euclidean}, L{cosineAndoyerLambert_},
557 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_}, L{equirectangular_},
558 L{flatLocal_}/L{hubeny_}, L{flatPolar_}, L{haversine_}, L{thomas_}
559 and L{vincentys_}.
560 '''
561 if adjust:
562 lam21 *= _scale_rad(phi2, phi1)
563 return euclid(phi2 - phi1, lam21)
566def excessAbc_(A, b, c):
567 '''Compute the I{spherical excess} C{E} of a (spherical) triangle
568 from two sides and the included angle.
570 @arg A: An interior triangle angle (C{radians}).
571 @arg b: Frist adjacent triangle side (C{radians}).
572 @arg c: Second adjacent triangle side (C{radians}).
574 @return: Spherical excess (C{radians}).
576 @raise UnitError: Invalid B{C{A}}, B{C{b}} or B{C{c}}.
578 @see: Functions L{excessGirard_}, L{excessLHuilier_} and U{Spherical
579 trigonometry<https://WikiPedia.org/wiki/Spherical_trigonometry>}.
580 '''
581 sA, cA, sb, cb, sc, cc = sincos2_(Radians_(A=A), Radians_(b=b) * _0_5,
582 Radians_(c=c) * _0_5)
583 return atan2(sA * sb * sc, cb * cc + cA * sb * sc) * _2_0
586def excessGirard_(A, B, C):
587 '''Compute the I{spherical excess} C{E} of a (spherical) triangle using
588 U{Girard's<https://MathWorld.Wolfram.com/GirardsSphericalExcessFormula.html>}
589 formula.
591 @arg A: First interior triangle angle (C{radians}).
592 @arg B: Second interior triangle angle (C{radians}).
593 @arg C: Third interior triangle angle (C{radians}).
595 @return: Spherical excess (C{radians}).
597 @raise UnitError: Invalid B{C{A}}, B{C{B}} or B{C{C}}.
599 @see: Function L{excessLHuilier_} and U{Spherical trigonometry
600 <https://WikiPedia.org/wiki/Spherical_trigonometry>}.
601 '''
602 return Radians(Girard=fsumf_(Radians_(A=A),
603 Radians_(B=B),
604 Radians_(C=C), -PI))
607def excessLHuilier_(a, b, c):
608 '''Compute the I{spherical excess} C{E} of a (spherical) triangle using
609 U{L'Huilier's<https://MathWorld.Wolfram.com/LHuiliersTheorem.html>}
610 Theorem.
612 @arg a: First triangle side (C{radians}).
613 @arg b: Second triangle side (C{radians}).
614 @arg c: Third triangle side (C{radians}).
616 @return: Spherical excess (C{radians}).
618 @raise UnitError: Invalid B{C{a}}, B{C{b}} or B{C{c}}.
620 @see: Function L{excessGirard_} and U{Spherical trigonometry
621 <https://WikiPedia.org/wiki/Spherical_trigonometry>}.
622 '''
623 a = Radians_(a=a)
624 b = Radians_(b=b)
625 c = Radians_(c=c)
627 s = fsumf_(a, b, c) * _0_5
628 r = tan_2(s) * tan_2(s - a) * tan_2(s - b) * tan_2(s - c)
629 r = atan(sqrt(r)) if r > 0 else _0_0
630 return Radians(LHuilier=r * _4_0)
633def excessKarney(lat1, lon1, lat2, lon2, radius=R_M, wrap=False):
634 '''Compute the surface area of a (spherical) quadrilateral bounded by a
635 segment of a great circle, two meridians and the equator using U{Karney's
636 <https://MathOverflow.net/questions/97711/the-area-of-spherical-polygons>}
637 method.
639 @arg lat1: Start latitude (C{degrees}).
640 @arg lon1: Start longitude (C{degrees}).
641 @arg lat2: End latitude (C{degrees}).
642 @arg lon2: End longitude (C{degrees}).
643 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum})
644 or ellipsoid (L{Ellipsoid}, L{Ellipsoid2} or
645 L{a_f2Tuple}) or C{None}.
646 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll
647 B{C{lat2}} and B{C{lon2}} (C{bool}).
649 @return: Surface area, I{signed} (I{square} C{meter} or the same units as
650 B{C{radius}} I{squared}) or the I{spherical excess} (C{radians})
651 if C{B{radius}=0} or C{None}.
653 @raise TypeError: Invalid B{C{radius}}.
655 @raise UnitError: Invalid B{C{lat2}} or B{C{lat1}}.
657 @raise ValueError: Semi-circular longitudinal delta.
659 @see: Functions L{excessKarney_} and L{excessQuad}.
660 '''
661 return _eA(excessKarney_, radius, wrap, lat1, lon1, lat2, lon2)
664def excessKarney_(phi2, phi1, lam21):
665 '''Compute the I{spherical excess} C{E} of a (spherical) quadrilateral bounded
666 by a segment of a great circle, two meridians and the equator using U{Karney's
667 <https://MathOverflow.net/questions/97711/the-area-of-spherical-polygons>}
668 method.
670 @arg phi2: End latitude (C{radians}).
671 @arg phi1: Start latitude (C{radians}).
672 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).
674 @return: Spherical excess, I{signed} (C{radians}).
676 @raise ValueError: Semi-circular longitudinal delta B{C{lam21}}.
678 @see: Function L{excessKarney} and U{Area of a spherical polygon
679 <https://MathOverflow.net/questions/97711/the-area-of-spherical-polygons>}.
680 '''
681 # from: Veness <https://www.Movable-Type.co.UK/scripts/latlong.html> Area
682 # method due to Karney: for each edge of the polygon,
683 #
684 # tan(Δλ / 2) · (tan(φ1 / 2) + tan(φ2 / 2))
685 # tan(E / 2) = -----------------------------------------
686 # 1 + tan(φ1 / 2) · tan(φ2 / 2)
687 #
688 # where E is the spherical excess of the trapezium obtained by extending
689 # the edge to the equator-circle vector for each edge (see also ***).
690 t2 = tan_2(phi2)
691 t1 = tan_2(phi1)
692 t = tan_2(lam21, lam21=None)
693 return Radians(Karney=atan2(t * (t1 + t2),
694 _1_0 + (t1 * t2)) * _2_0)
697# ***) Original post no longer available, following is a copy of the main part
698# <http://OSGeo-org.1560.x6.Nabble.com/Area-of-a-spherical-polygon-td3841625.html>
699#
700# The area of a polygon on a (unit) sphere is given by the spherical excess
701#
702# A = 2 * pi - sum(exterior angles)
703#
704# However this is badly conditioned if the polygon is small. In this case, use
705#
706# A = sum(S12{i, i+1}) over the edges of the polygon
707#
708# where S12 is the area of the quadrilateral bounded by an edge of the polygon,
709# two meridians and the equator, i.e. with vertices (phi1, lambda1), (phi2,
710# lambda2), (0, lambda1) and (0, lambda2). S12 is given by
711#
712# tan(S12 / 2) = tan(lambda21 / 2) * (tan(phi1 / 2) + tan(phi2 / 2)) /
713# (tan(phi1 / 2) * tan(phi2 / 2) + 1)
714#
715# = tan(lambda21 / 2) * tanh((Lambertian(phi1) +
716# Lambertian(phi2)) / 2)
717#
718# where lambda21 = lambda2 - lambda1 and lamb(x) is the Lambertian (or
719# inverse Gudermannian) function
720#
721# Lambertian(x) = asinh(tan(x)) = atanh(sin(x)) = 2 * atanh(tan(x / 2))
722#
723# Notes: The formula for S12 is exact, except that...
724# - it is indeterminate if an edge is a semi-circle
725# - the formula for A applies only if the polygon does not include a pole
726# (if it does, then add +/- 2 * pi to the result)
727# - in the limit of small phi and lambda, S12 reduces to the trapezoidal
728# formula, S12 = (lambda2 - lambda1) * (phi1 + phi2) / 2
729# - I derived this result from the equation for the area of a spherical
730# triangle in terms of two edges and the included angle given by, e.g.
731# U{Todhunter, I. - Spherical Trigonometry (1871), Sec. 103, Eq. (2)
732# <http://Books.Google.com/books?id=3uBHAAAAIAAJ&pg=PA71>}
733# - I would be interested to know if this formula for S12 is already known
734# - Charles Karney
737def excessQuad(lat1, lon1, lat2, lon2, radius=R_M, wrap=False):
738 '''Compute the surface area of a (spherical) quadrilateral bounded by a segment
739 of a great circle, two meridians and the equator.
741 @arg lat1: Start latitude (C{degrees}).
742 @arg lon1: Start longitude (C{degrees}).
743 @arg lat2: End latitude (C{degrees}).
744 @arg lon2: End longitude (C{degrees}).
745 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum})
746 or ellipsoid (L{Ellipsoid}, L{Ellipsoid2} or
747 L{a_f2Tuple}) or C{None}.
748 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll
749 B{C{lat2}} and B{C{lon2}} (C{bool}).
751 @return: Surface area, I{signed} (I{square} C{meter} or the same units as
752 B{C{radius}} I{squared}) or the I{spherical excess} (C{radians})
753 if C{B{radius}=0} or C{None}.
755 @raise TypeError: Invalid B{C{radius}}.
757 @raise UnitError: Invalid B{C{lat2}} or B{C{lat1}}.
759 @see: Function L{excessQuad_} and L{excessKarney}.
760 '''
761 return _eA(excessQuad_, radius, wrap, lat1, lon1, lat2, lon2)
764def excessQuad_(phi2, phi1, lam21):
765 '''Compute the I{spherical excess} C{E} of a (spherical) quadrilateral bounded
766 by a segment of a great circle, two meridians and the equator.
768 @arg phi2: End latitude (C{radians}).
769 @arg phi1: Start latitude (C{radians}).
770 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).
772 @return: Spherical excess, I{signed} (C{radians}).
774 @see: Function L{excessQuad}, U{Spherical trigonometry
775 <https://WikiPedia.org/wiki/Spherical_trigonometry>}.
776 '''
777 s = sin((phi2 + phi1) * _0_5)
778 c = cos((phi2 - phi1) * _0_5)
779 return Radians(Quad=atan2(tan_2(lam21) * s, c) * _2_0)
782def flatLocal(lat1, lon1, lat2, lon2, datum=_WGS84, scaled=True, wrap=False):
783 '''Compute the distance between two (ellipsoidal) points using
784 the U{ellipsoidal Earth to plane projection<https://WikiPedia.org/
785 wiki/Geographical_distance#Ellipsoidal_Earth_projected_to_a_plane>}
786 aka U{Hubeny<https://www.OVG.AT/de/vgi/files/pdf/3781/>} formula.
788 @arg lat1: Start latitude (C{degrees}).
789 @arg lon1: Start longitude (C{degrees}).
790 @arg lat2: End latitude (C{degrees}).
791 @arg lon2: End longitude (C{degrees}).
792 @kwarg datum: Datum (L{Datum}) or ellipsoid (L{Ellipsoid},
793 L{Ellipsoid2} or L{a_f2Tuple}) to use.
794 @kwarg scaled: Scale prime_vertical by C{cos(B{phi})} (C{bool}),
795 see method L{pygeodesy.Ellipsoid.roc2_}.
796 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll
797 B{C{lat2}} and B{C{lon2}} (C{bool}).
799 @return: Distance (C{meter}, same units as the B{C{datum}}'s
800 ellipsoid axes).
802 @raise TypeError: Invalid B{C{datum}}.
804 @note: The meridional and prime_vertical radii of curvature
805 are taken and scaled at the mean of both latitude.
807 @see: Functions L{flatLocal_} or L{hubeny_}, L{cosineLaw}, L{flatPolar},
808 L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},
809 L{equirectangular}, L{euclidean}, L{haversine}, L{thomas},
810 L{vincentys}, method L{Ellipsoid.distance2} and U{local, flat
811 earth approximation<https://www.EdWilliams.org/avform.htm#flat>}.
812 '''
813 E = _ellipsoidal(datum, flatLocal)
814 return E._hubeny_2(*_d3(wrap, lat1, lon1, lat2, lon2),
815 scaled=scaled, squared=False) * E.a
817hubeny = flatLocal # PYCHOK for Karl Hubeny
820def flatLocal_(phi2, phi1, lam21, datum=_WGS84, scaled=True):
821 '''Compute the I{angular} distance between two (ellipsoidal) points using
822 the U{ellipsoidal Earth to plane projection<https://WikiPedia.org/
823 wiki/Geographical_distance#Ellipsoidal_Earth_projected_to_a_plane>}
824 aka U{Hubeny<https://www.OVG.AT/de/vgi/files/pdf/3781/>} formula.
826 @arg phi2: End latitude (C{radians}).
827 @arg phi1: Start latitude (C{radians}).
828 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).
829 @kwarg datum: Datum (L{Datum}) or ellipsoid (L{Ellipsoid},
830 L{Ellipsoid2} or L{a_f2Tuple}) to use.
831 @kwarg scaled: Scale prime_vertical by C{cos(B{phi})} (C{bool}),
832 see method L{pygeodesy.Ellipsoid.roc2_}.
834 @return: Angular distance (C{radians}).
836 @raise TypeError: Invalid B{C{datum}}.
838 @note: The meridional and prime_vertical radii of curvature
839 are taken and scaled I{at the mean of both latitude}.
841 @see: Functions L{flatLocal} or L{hubeny}, L{cosineAndoyerLambert_},
842 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_}, L{flatPolar_},
843 L{equirectangular_}, L{euclidean_}, L{haversine_}, L{thomas_}
844 and L{vincentys_} and U{local, flat earth approximation
845 <https://www.EdWilliams.org/avform.htm#flat>}.
846 '''
847 E = _ellipsoidal(datum, flatLocal_)
848 return E._hubeny_2(phi2, phi1, lam21, scaled=scaled, squared=False)
850hubeny_ = flatLocal_ # PYCHOK for Karl Hubeny
853def flatPolar(lat1, lon1, lat2, lon2, radius=R_M, wrap=False):
854 '''Compute the distance between two (spherical) points using
855 the U{polar coordinate flat-Earth <https://WikiPedia.org/wiki/
856 Geographical_distance#Polar_coordinate_flat-Earth_formula>}
857 formula.
859 @arg lat1: Start latitude (C{degrees}).
860 @arg lon1: Start longitude (C{degrees}).
861 @arg lat2: End latitude (C{degrees}).
862 @arg lon2: End longitude (C{degrees}).
863 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum})
864 or ellipsoid (L{Ellipsoid}, L{Ellipsoid2} or
865 L{a_f2Tuple}) to use.
866 @kwarg wrap: If C{True}, wrap or I{normalize} and B{C{lat2}}
867 and B{C{lon2}} (C{bool}).
869 @return: Distance (C{meter}, same units as B{C{radius}} or the
870 ellipsoid or datum axes).
872 @raise TypeError: Invalid B{C{radius}}.
874 @see: Functions L{flatPolar_}, L{cosineAndoyerLambert},
875 L{cosineForsytheAndoyerLambert},L{cosineLaw},
876 L{flatLocal}/L{hubeny}, L{equirectangular},
877 L{euclidean}, L{haversine}, L{thomas} and
878 L{vincentys}.
879 '''
880 return _dS(flatPolar_, radius, wrap, lat1, lon1, lat2, lon2)
883def flatPolar_(phi2, phi1, lam21):
884 '''Compute the I{angular} distance between two (spherical) points
885 using the U{polar coordinate flat-Earth<https://WikiPedia.org/wiki/
886 Geographical_distance#Polar_coordinate_flat-Earth_formula>}
887 formula.
889 @arg phi2: End latitude (C{radians}).
890 @arg phi1: Start latitude (C{radians}).
891 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).
893 @return: Angular distance (C{radians}).
895 @see: Functions L{flatPolar}, L{cosineAndoyerLambert_},
896 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},
897 L{equirectangular_}, L{euclidean_}, L{flatLocal_}/L{hubeny_},
898 L{haversine_}, L{thomas_} and L{vincentys_}.
899 '''
900 a = fabs(PI_2 - phi1) # co-latitude
901 b = fabs(PI_2 - phi2) # co-latitude
902 if a < b:
903 a, b = b, a
904 if a < EPS0:
905 a = _0_0
906 elif b > 0:
907 b = b / a # /= chokes PyChecker
908 c = b * cos(lam21) * _2_0
909 c = fsumf_(_1_0, b**2, -fabs(c))
910 a *= sqrt0(c)
911 return a
914def hartzell(pov, los=None, earth=_WGS84, name=NN, **LatLon_and_kwds):
915 '''Compute the intersection of the earth's surface and a Line-Of-Sight
916 from a Point-Of-View in space.
918 @arg pov: Point-Of-View outside the earth (C{Cartesian}, L{Ecef9Tuple}
919 or L{Vector3d}).
920 @kwarg los: Line-Of-Sight, I{direction} to earth (L{Vector3d}) or
921 C{None} to point to the earth' center.
922 @kwarg earth: The earth model (L{Datum}, L{Ellipsoid}, L{Ellipsoid2},
923 L{a_f2Tuple} or C{scalar} radius in C{meter}).
924 @kwarg name: Optional name (C{str}).
925 @kwarg LatLon_and_kwds: Optional C{LatLon} class for the intersection
926 point plus C{LatLon} keyword arguments, include
927 B{C{datum}} if different from B{C{earth}}.
929 @return: The earth intersection (L{Vector3d}, C{Cartesian type} of
930 B{C{pov}} or B{C{LatLon}}).
932 @raise IntersectionError: Null B{C{pov}} or B{C{los}} vector, B{C{pov}}
933 is inside the earth or B{C{los}} points outside
934 the earth or points in an opposite direction.
936 @raise TypeError: Invalid B{C{pov}}, B{C{los}} or B{C{earth}}.
938 @see: Function L{pygeodesy.hartzell4}, L{pygeodesy.tyr3d} for B{C{los}},
939 method L{Ellipsoid.hartzell4} and U{I{Satellite Line-of-Sight
940 Intersection with Earth}<https://StephenHartzell.Medium.com/
941 satellite-line-of-sight-intersection-with-earth-d786b4a6a9b6>}.
942 '''
943 D = earth if isinstance(earth, Datum) else \
944 _spherical_datum(earth, name=hartzell.__name__)
945 try:
946 r, _ = _MODS.triaxials._hartzell3d2(pov, los, D.ellipsoid._triaxial)
947 except Exception as x:
948 raise IntersectionError(pov=pov, los=los, earth=earth, cause=x)
950# else:
951# E = D.ellipsoid
952# # Triaxial(a, b, c) == (E.a, E.a, E.b)
953#
954# def _Error(txt):
955# return IntersectionError(pov=pov, los=los, earth=earth, txt=txt)
956#
957# a2 = b2 = E.a2 # earth' x, y, ...
958# c2 = E.b2 # ... z semi-axis squared
959# q2 = E.b2_a2 # == c2 / a2
960# bc = E.a * E.b # == b * c
961#
962# V3 = _MODS.vector3d._otherV3d
963# p3 = V3(pov=pov)
964# u3 = V3(los=los) if los else p3.negate()
965# u3 = u3.unit() # unit vector, opposing signs
966#
967# x2, y2, z2 = p3.x2y2z2 # p3.times_(p3).xyz
968# ux, vy, wz = u3.times_(p3).xyz
969# u2, v2, w2 = u3.x2y2z2 # u3.times_(u3).xyz
970#
971# t = c2, c2, b2
972# m = fdot(t, u2, v2, w2) # a2 factored out
973# if m < EPS0: # zero or near-null LOS vector
974# raise _Error(_near_(_null_))
975#
976# # a2 and b2 factored out, b2 == a2 and b2 / a2 == 1
977# r = fsumf_(b2 * w2, c2 * v2, -v2 * z2, vy * wz * 2,
978# c2 * u2, -u2 * z2, -w2 * x2, ux * wz * 2,
979# -w2 * y2, -u2 * y2 * q2, -v2 * x2 * q2, ux * vy * 2 * q2)
980# if r > 0:
981# r = sqrt(r) * bc # == a * a * b * c / a2
982# elif r < 0: # LOS pointing away from or missing the earth
983# raise _Error(_opposite_ if max(ux, vy, wz) > 0 else _outside_)
984#
985# d = Fdot(t, ux, vy, wz).fadd_(r).fover(m) # -r for antipode, a2 factored out
986# if d > 0: # POV inside or LOS missing, outside the earth
987# s = fsumf_(_1_0, x2 / a2, y2 / b2, z2 / c2, _N_2_0) # like _sideOf
988# raise _Error(_outside_ if s > 0 else _inside_)
989# elif fsumf_(x2, y2, z2) < d**2: # d past earth center
990# raise _Error(_too_(_distant_))
991#
992# r = p3.minus(u3.times(d))
993# # h = p3.minus(r).length # distance to ellipsoid
995 r = _xnamed(r, name or hartzell.__name__)
996 if LatLon_and_kwds:
997 c = _MODS.cartesianBase.CartesianBase(r, datum=D, name=r.name)
998 r = c.toLatLon(**LatLon_and_kwds)
999 return r
1002def haversine(lat1, lon1, lat2, lon2, radius=R_M, wrap=False):
1003 '''Compute the distance between two (spherical) points using the
1004 U{Haversine<https://www.Movable-Type.co.UK/scripts/latlong.html>}
1005 formula.
1007 @arg lat1: Start latitude (C{degrees}).
1008 @arg lon1: Start longitude (C{degrees}).
1009 @arg lat2: End latitude (C{degrees}).
1010 @arg lon2: End longitude (C{degrees}).
1011 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum})
1012 or ellipsoid (L{Ellipsoid}, L{Ellipsoid2} or
1013 L{a_f2Tuple}) to use.
1014 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll
1015 B{C{lat2}} and B{C{lon2}} (C{bool}).
1017 @return: Distance (C{meter}, same units as B{C{radius}}).
1019 @raise TypeError: Invalid B{C{radius}}.
1021 @see: U{Distance between two (spherical) points
1022 <https://www.EdWilliams.org/avform.htm#Dist>}, functions
1023 L{cosineLaw}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},
1024 L{equirectangular}, L{euclidean}, L{flatLocal}/L{hubeny}, L{flatPolar},
1025 L{thomas} and L{vincentys} and methods L{Ellipsoid.distance2},
1026 C{LatLon.distanceTo*} and C{LatLon.equirectangularTo}.
1028 @note: See note at function L{vincentys_}.
1029 '''
1030 return _dS(haversine_, radius, wrap, lat1, lon1, lat2, lon2)
1033def haversine_(phi2, phi1, lam21):
1034 '''Compute the I{angular} distance between two (spherical) points
1035 using the U{Haversine<https://www.Movable-Type.co.UK/scripts/latlong.html>}
1036 formula.
1038 @arg phi2: End latitude (C{radians}).
1039 @arg phi1: Start latitude (C{radians}).
1040 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).
1042 @return: Angular distance (C{radians}).
1044 @see: Functions L{haversine}, L{cosineAndoyerLambert_},
1045 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},
1046 L{equirectangular_}, L{euclidean_}, L{flatLocal_}/L{hubeny_},
1047 L{flatPolar_}, L{thomas_} and L{vincentys_}.
1049 @note: See note at function L{vincentys_}.
1050 '''
1051 def _hsin(rad):
1052 return sin(rad * _0_5)**2
1054 h = _hsin(phi2 - phi1) + cos(phi1) * cos(phi2) * _hsin(lam21) # haversine
1055 return atan2(sqrt0(h), sqrt0(_1_0 - h)) * _2_0 # == asin(sqrt(h)) * 2
1058def heightOf(angle, distance, radius=R_M):
1059 '''Determine the height above the (spherical) earth' surface after
1060 traveling along a straight line at a given tilt.
1062 @arg angle: Tilt angle above horizontal (C{degrees}).
1063 @arg distance: Distance along the line (C{meter} or same units as
1064 B{C{radius}}).
1065 @kwarg radius: Optional mean earth radius (C{meter}).
1067 @return: Height (C{meter}, same units as B{C{distance}} and B{C{radius}}).
1069 @raise ValueError: Invalid B{C{angle}}, B{C{distance}} or B{C{radius}}.
1071 @see: U{MultiDop geog_lib.GeogBeamHt<https://GitHub.com/NASA/MultiDop>}
1072 (U{Shapiro et al. 2009, JTECH
1073 <https://Journals.AMetSoc.org/doi/abs/10.1175/2009JTECHA1256.1>}
1074 and U{Potvin et al. 2012, JTECH
1075 <https://Journals.AMetSoc.org/doi/abs/10.1175/JTECH-D-11-00019.1>}).
1076 '''
1077 r = h = Radius(radius)
1078 d = fabs(Distance(distance))
1079 if d > h:
1080 d, h = h, d
1082 if d > EPS0: # and h > EPS0
1083 d = d / h # /= h chokes PyChecker
1084 s = sin(Phi_(angle=angle, clip=_180_0))
1085 s = fsumf_(_1_0, _2_0 * s * d, d**2)
1086 if s > 0:
1087 return h * sqrt(s) - r
1089 raise _ValueError(angle=angle, distance=distance, radius=radius)
1092def horizon(height, radius=R_M, refraction=False):
1093 '''Determine the distance to the horizon from a given altitude
1094 above the (spherical) earth.
1096 @arg height: Altitude (C{meter} or same units as B{C{radius}}).
1097 @kwarg radius: Optional mean earth radius (C{meter}).
1098 @kwarg refraction: Consider atmospheric refraction (C{bool}).
1100 @return: Distance (C{meter}, same units as B{C{height}} and B{C{radius}}).
1102 @raise ValueError: Invalid B{C{height}} or B{C{radius}}.
1104 @see: U{Distance to horizon<https://www.EdWilliams.org/avform.htm#Horizon>}.
1105 '''
1106 h, r = Height(height), Radius(radius)
1107 if min(h, r) < 0:
1108 raise _ValueError(height=height, radius=radius)
1110 if refraction:
1111 d2 = 2.415750694528 * h * r # 2.0 / 0.8279
1112 else:
1113 d2 = h * fsumf_(r, r, h)
1114 return sqrt0(d2)
1117class _idllmn6(object): # see also .geodesicw._wargs, .vector2d._numpy
1118 '''(INTERNAL) Helper for C{intersection2} and C{intersections2}.
1119 '''
1120 @contextmanager # <https://www.python.org/dev/peps/pep-0343/> Examples
1121 def __call__(self, datum, lat1, lon1, lat2, lon2, small, wrap, s, **kwds):
1122 try:
1123 if wrap:
1124 _, lat2, lon2 = _Wrap.latlon3(lon1, lat2, lon2, wrap)
1125 kwds = _xkwds(kwds, wrap=wrap) # for _xError
1126 m = small if small is _100km else Meter_(small=small)
1127 n = (intersections2 if s else intersection2).__name__
1128 if datum is None or euclidean(lat1, lon1, lat2, lon2) < m:
1129 d, m = None, _MODS.vector3d
1130 _i = m._intersects2 if s else m._intersect3d3
1131 elif isscalar(datum) and datum < 0 and not s:
1132 d = _spherical_datum(-datum, name=n)
1133 m = _MODS.sphericalNvector
1134 _i = m.intersection
1135 else:
1136 d = _spherical_datum(datum, name=n)
1137 if d.isSpherical:
1138 m = _MODS.sphericalTrigonometry
1139 _i = m._intersects2 if s else m._intersect
1140 elif d.isEllipsoidal:
1141 try:
1142 if d.ellipsoid.geodesic:
1143 pass
1144 m = _MODS.ellipsoidalKarney
1145 except ImportError:
1146 m = _MODS.ellipsoidalExact
1147 _i = m._intersections2 if s else m._intersection3 # ellispoidalBaseDI
1148 else:
1149 raise _TypeError(datum=datum)
1150 yield _i, d, lat2, lon2, m, n
1152 except (TypeError, ValueError) as x:
1153 raise _xError(x, lat1=lat1, lon1=lon1, datum=datum,
1154 lat2=lat2, lon2=lon2, small=small, **kwds)
1156_idllmn6 = _idllmn6() # PYCHOK singleton
1159def intersection2(lat1, lon1, bearing1,
1160 lat2, lon2, bearing2, datum=None, wrap=False, small=_100km): # was=True
1161 '''I{Conveniently} compute the intersection of two lines each defined
1162 by a (geodetic) point and a bearing from North, using either ...
1164 1) L{vector3d.intersection3d3} for B{C{small}} distances (below 100 Km
1165 or about 0.88 degrees) or if I{no} B{C{datum}} is specified, or ...
1167 2) L{sphericalTrigonometry.intersection} for a spherical B{C{datum}}
1168 or a C{scalar B{datum}} representing the earth radius, conventionally
1169 in C{meter} or ...
1171 3) L{sphericalNvector.intersection} if B{C{datum}} is a I{negative}
1172 C{scalar}, (negative) earth radius, conventionally in C{meter} or ...
1174 4) L{ellipsoidalKarney.intersection3} for an ellipsoidal B{C{datum}}
1175 and if I{Karney}'s U{geographiclib<https://PyPI.org/project/geographiclib>}
1176 is installed, otherwise ...
1178 5) L{ellipsoidalExact.intersection3}, provided B{C{datum}} is ellipsoidal.
1180 @arg lat1: Latitude of the first point (C{degrees}).
1181 @arg lon1: Longitude of the first point (C{degrees}).
1182 @arg bearing1: Bearing at the first point (compass C{degrees}).
1183 @arg lat2: Latitude of the second point (C{degrees}).
1184 @arg lon2: Longitude of the second point (C{degrees}).
1185 @arg bearing2: Bearing at the second point (compass C{degrees}).
1186 @kwarg datum: Optional datum (L{Datum}) or ellipsoid (L{Ellipsoid},
1187 L{Ellipsoid2} or L{a_f2Tuple}) or C{scalar} earth
1188 radius (C{meter}, same units as B{C{radius1}} and
1189 B{C{radius2}}) or C{None}.
1190 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll B{C{lat2}}
1191 and B{C{lon2}} (C{bool}).
1192 @kwarg small: Upper limit for small distances (C{meter}).
1194 @return: A L{LatLon2Tuple}C{(lat, lon)} with the lat- and
1195 longitude of the intersection point.
1197 @raise IntersectionError: Ambiguous or infinite intersection
1198 or colinear, parallel or otherwise
1199 non-intersecting lines.
1201 @raise TypeError: Invalid B{C{datum}}.
1203 @raise UnitError: Invalid B{C{lat1}}, B{C{lon1}}, B{C{bearing1}},
1204 B{C{lat2}}, B{C{lon2}} or B{C{bearing2}}.
1206 @see: Method L{RhumbLine.intersection2}.
1208 @note: The returned intersections may be near-antipodal.
1209 '''
1210 b1 = Bearing(bearing1=bearing1)
1211 b2 = Bearing(bearing2=bearing2)
1212 with _idllmn6(datum, lat1, lon1, lat2, lon2,
1213 small, wrap, False, bearing1=b1, bearing2=b2) as t:
1214 _i, d, lat2, lon2, m, n = t
1215 if d is None:
1216 t, _, _ = _i(m.Vector3d(lon1, lat1, 0), b1,
1217 m.Vector3d(lon2, lat2, 0), b2, useZ=False)
1218 t = LatLon2Tuple(t.y, t.x, name=n)
1220 else:
1221 t = _i(m.LatLon(lat1, lon1, datum=d), b1,
1222 m.LatLon(lat2, lon2, datum=d), b2, height=0, wrap=False)
1223 if isinstance(t, Intersection3Tuple): # ellipsoidal
1224 t, _, _ = t
1225 t = LatLon2Tuple(t.lat, t.lon, name=n)
1226 return t
1229def intersections2(lat1, lon1, radius1,
1230 lat2, lon2, radius2, datum=None, wrap=False, small=_100km): # was=True
1231 '''I{Conveniently} compute the intersections of two circles each defined
1232 by a (geodetic) center point and a radius, using either ...
1234 1) L{vector3d.intersections2} for B{C{small}} distances (below 100 Km
1235 or about 0.88 degrees) or if I{no} B{C{datum}} is specified, or ...
1237 2) L{sphericalTrigonometry.intersections2} for a spherical B{C{datum}}
1238 or a C{scalar B{datum}} representing the earth radius, conventionally
1239 in C{meter} or ...
1241 3) L{ellipsoidalKarney.intersections2} for an ellipsoidal B{C{datum}}
1242 and if I{Karney}'s U{geographiclib<https://PyPI.org/project/geographiclib>}
1243 is installed, otherwise ...
1245 4) L{ellipsoidalExact.intersections2}, provided B{C{datum}} is ellipsoidal.
1247 @arg lat1: Latitude of the first circle center (C{degrees}).
1248 @arg lon1: Longitude of the first circle center (C{degrees}).
1249 @arg radius1: Radius of the first circle (C{meter}, conventionally).
1250 @arg lat2: Latitude of the second circle center (C{degrees}).
1251 @arg lon2: Longitude of the second circle center (C{degrees}).
1252 @arg radius2: Radius of the second circle (C{meter}, same units as B{C{radius1}}).
1253 @kwarg datum: Optional datum (L{Datum}) or ellipsoid (L{Ellipsoid},
1254 L{Ellipsoid2} or L{a_f2Tuple}) or C{scalar} earth
1255 radius (C{meter}, same units as B{C{radius1}} and
1256 B{C{radius2}}) or C{None}.
1257 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll B{C{lat2}}
1258 and B{C{lon2}} (C{bool}).
1259 @kwarg small: Upper limit for small distances (C{meter}).
1261 @return: 2-Tuple of the intersection points, each a
1262 L{LatLon2Tuple}C{(lat, lon)}. For abutting circles, the
1263 points are the same instance, aka the I{radical center}.
1265 @raise IntersectionError: Concentric, antipodal, invalid or
1266 non-intersecting circles or no
1267 convergence.
1269 @raise TypeError: Invalid B{C{datum}}.
1271 @raise UnitError: Invalid B{C{lat1}}, B{C{lon1}}, B{C{radius1}},
1272 B{C{lat2}}, B{C{lon2}} or B{C{radius2}}.
1273 '''
1274 r1 = Radius_(radius1=radius1)
1275 r2 = Radius_(radius2=radius2)
1276 with _idllmn6(datum, lat1, lon1, lat2, lon2,
1277 small, wrap, True, radius1=r1, radius2=r2) as t:
1278 _i, d, lat2, lon2, m, n = t
1279 if d is None:
1280 r1 = m2degrees(r1, radius=R_M, lat=lat1)
1281 r2 = m2degrees(r2, radius=R_M, lat=lat2)
1283 def _V2T(x, y, _, **unused): # _ == z unused
1284 return LatLon2Tuple(y, x, name=n)
1286 t = _i(m.Vector3d(lon1, lat1, 0), r1,
1287 m.Vector3d(lon2, lat2, 0), r2, sphere=False,
1288 Vector=_V2T)
1289 else:
1290 def _LL2T(lat, lon, **unused):
1291 return LatLon2Tuple(lat, lon, name=n)
1293 t = _i(m.LatLon(lat1, lon1, datum=d), r1,
1294 m.LatLon(lat2, lon2, datum=d), r2,
1295 LatLon=_LL2T, height=0, wrap=False)
1296 return t
1299def isantipode(lat1, lon1, lat2, lon2, eps=EPS):
1300 '''Check whether two points are I{antipodal}, on diametrically
1301 opposite sides of the earth.
1303 @arg lat1: Latitude of one point (C{degrees}).
1304 @arg lon1: Longitude of one point (C{degrees}).
1305 @arg lat2: Latitude of the other point (C{degrees}).
1306 @arg lon2: Longitude of the other point (C{degrees}).
1307 @kwarg eps: Tolerance for near-equality (C{degrees}).
1309 @return: C{True} if points are antipodal within the
1310 B{C{eps}} tolerance, C{False} otherwise.
1312 @see: Functions L{isantipode_} and L{antipode}.
1313 '''
1314 return (fabs(lat1 + lat2) <= eps and
1315 fabs(lon1 + lon2) <= eps) or _isequalTo(
1316 normal(lat1, lon1), antipode(lat2, lon2), eps)
1319def isantipode_(phi1, lam1, phi2, lam2, eps=EPS):
1320 '''Check whether two points are I{antipodal}, on diametrically
1321 opposite sides of the earth.
1323 @arg phi1: Latitude of one point (C{radians}).
1324 @arg lam1: Longitude of one point (C{radians}).
1325 @arg phi2: Latitude of the other point (C{radians}).
1326 @arg lam2: Longitude of the other point (C{radians}).
1327 @kwarg eps: Tolerance for near-equality (C{radians}).
1329 @return: C{True} if points are antipodal within the
1330 B{C{eps}} tolerance, C{False} otherwise.
1332 @see: Functions L{isantipode} and L{antipode_}.
1333 '''
1334 return (fabs(phi1 + phi2) <= eps and
1335 fabs(lam1 + lam2) <= eps) or _isequalTo_(
1336 normal_(phi1, lam1), antipode_(phi2, lam2), eps)
1339def _isequalTo(p1, p2, eps=EPS):
1340 '''Compare 2 point lat-/lons ignoring C{class}.
1341 '''
1342 return (fabs(p1.lat - p2.lat) <= eps and
1343 fabs(p1.lon - p2.lon) <= eps) if eps else (p1.latlon == p2.latlon)
1346def _isequalTo_(p1, p2, eps=EPS):
1347 '''(INTERNAL) Compare 2 point phi-/lams ignoring C{class}.
1348 '''
1349 return (fabs(p1.phi - p2.phi) <= eps and
1350 fabs(p1.lam - p2.lam) <= eps) if eps else (p1.philam == p2.philam)
1353def isnormal(lat, lon, eps=0):
1354 '''Check whether B{C{lat}} I{and} B{C{lon}} are within their
1355 respective I{normal} range in C{degrees}.
1357 @arg lat: Latitude (C{degrees}).
1358 @arg lon: Longitude (C{degrees}).
1359 @kwarg eps: Optional tolerance C{degrees}).
1361 @return: C{True} if C{(abs(B{lat}) + B{eps}) <= 90} and
1362 C{(abs(B{lon}) + B{eps}) <= 180}, C{False} othwerwise.
1364 @see: Functions L{isnormal_} and L{normal}.
1365 '''
1366 return (_90_0 - fabs(lat)) >= eps and (_180_0 - fabs(lon)) >= eps
1369def isnormal_(phi, lam, eps=0):
1370 '''Check whether B{C{phi}} I{and} B{C{lam}} are within their
1371 respective I{normal} range in C{radians}.
1373 @arg phi: Latitude (C{radians}).
1374 @arg lam: Longitude (C{radians}).
1375 @kwarg eps: Optional tolerance C{radians}).
1377 @return: C{True} if C{(abs(B{phi}) + B{eps}) <= PI/2} and
1378 C{(abs(B{lam}) + B{eps}) <= PI}, C{False} othwerwise.
1380 @see: Functions L{isnormal} and L{normal_}.
1381 '''
1382 return (PI_2 - fabs(phi)) >= eps and (PI - fabs(lam)) >= eps
1385def latlon2n_xyz(lat, lon, name=NN):
1386 '''Convert lat-, longitude to C{n-vector} (I{normal} to the
1387 earth's surface) X, Y and Z components.
1389 @arg lat: Latitude (C{degrees}).
1390 @arg lon: Longitude (C{degrees}).
1391 @kwarg name: Optional name (C{str}).
1393 @return: A L{Vector3Tuple}C{(x, y, z)}.
1395 @see: Function L{philam2n_xyz}.
1397 @note: These are C{n-vector} x, y and z components,
1398 I{NOT} geocentric ECEF x, y and z coordinates!
1399 '''
1400 return _2n_xyz(name, *sincos2d_(lat, lon))
1403def _normal2(a, b, n_2, n, n2):
1404 '''(INTERNAL) Helper for C{normal} and C{normal_}.
1405 '''
1406 if fabs(b) > n:
1407 b = remainder(b, n2)
1408 if fabs(a) > n_2:
1409 r = remainder(a, n)
1410 if r != a:
1411 a = -r
1412 b -= n if b > 0 else -n
1413 return float0_(a, b)
1416def normal(lat, lon, name=NN):
1417 '''Normalize a lat- I{and} longitude pair in C{degrees}.
1419 @arg lat: Latitude (C{degrees}).
1420 @arg lon: Longitude (C{degrees}).
1421 @kwarg name: Optional name (C{str}).
1423 @return: L{LatLon2Tuple}C{(lat, lon)} with C{abs(lat) <= 90}
1424 and C{abs(lon) <= 180}.
1426 @see: Functions L{normal_} and L{isnormal}.
1427 '''
1428 return LatLon2Tuple(*_normal2(lat, lon, _90_0, _180_0, _360_0),
1429 name=name or normal.__name__)
1432def normal_(phi, lam, name=NN):
1433 '''Normalize a lat- I{and} longitude pair in C{radians}.
1435 @arg phi: Latitude (C{radians}).
1436 @arg lam: Longitude (C{radians}).
1437 @kwarg name: Optional name (C{str}).
1439 @return: L{PhiLam2Tuple}C{(phi, lam)} with C{abs(phi) <= PI/2}
1440 and C{abs(lam) <= PI}.
1442 @see: Functions L{normal} and L{isnormal_}.
1443 '''
1444 return PhiLam2Tuple(*_normal2(phi, lam, PI_2, PI, PI2),
1445 name=name or normal_.__name__)
1448def _2n_xyz(name, sa, ca, sb, cb):
1449 '''(INTERNAL) Helper for C{latlon2n_xyz} and C{philam2n_xyz}.
1450 '''
1451 # Kenneth Gade eqn 3, but using right-handed
1452 # vector x -> 0°E,0°N, y -> 90°E,0°N, z -> 90°N
1453 return Vector3Tuple(ca * cb, ca * sb, sa, name=name)
1456def n_xyz2latlon(x, y, z, name=NN):
1457 '''Convert C{n-vector} components to lat- and longitude in C{degrees}.
1459 @arg x: X component (C{scalar}).
1460 @arg y: Y component (C{scalar}).
1461 @arg z: Z component (C{scalar}).
1462 @kwarg name: Optional name (C{str}).
1464 @return: A L{LatLon2Tuple}C{(lat, lon)}.
1466 @see: Function L{n_xyz2philam}.
1467 '''
1468 return LatLon2Tuple(atan2d(z, hypot(x, y)), atan2d(y, x), name=name)
1471def n_xyz2philam(x, y, z, name=NN):
1472 '''Convert C{n-vector} components to lat- and longitude in C{radians}.
1474 @arg x: X component (C{scalar}).
1475 @arg y: Y component (C{scalar}).
1476 @arg z: Z component (C{scalar}).
1477 @kwarg name: Optional name (C{str}).
1479 @return: A L{PhiLam2Tuple}C{(phi, lam)}.
1481 @see: Function L{n_xyz2latlon}.
1482 '''
1483 return PhiLam2Tuple(atan2(z, hypot(x, y)), atan2(y, x), name=name)
1486def _opposes(d, m, n, n2):
1487 '''(INETNAL) Helper for C{opposing} and C{opposing_}.
1488 '''
1489 d = d % n2 # -20 % 360 == 340, -1 % PI2 == PI2 - 1
1490 return False if d < m or d > (n2 - m) else (
1491 True if (n - m) < d < (n + m) else None)
1494def opposing(bearing1, bearing2, margin=_90_0):
1495 '''Compare the direction of two bearings given in C{degrees}.
1497 @arg bearing1: First bearing (compass C{degrees}).
1498 @arg bearing2: Second bearing (compass C{degrees}).
1499 @kwarg margin: Optional, interior angle bracket (C{degrees}).
1501 @return: C{True} if both bearings point in opposite, C{False} if
1502 in similar or C{None} if in perpendicular directions.
1504 @see: Function L{opposing_}.
1505 '''
1506 m = Degrees_(margin=margin, low=EPS0, high=_90_0)
1507 return _opposes(bearing2 - bearing1, m,_180_0, _360_0)
1510def opposing_(radians1, radians2, margin=PI_2):
1511 '''Compare the direction of two bearings given in C{radians}.
1513 @arg radians1: First bearing (C{radians}).
1514 @arg radians2: Second bearing (C{radians}).
1515 @kwarg margin: Optional, interior angle bracket (C{radians}).
1517 @return: C{True} if both bearings point in opposite, C{False} if
1518 in similar or C{None} if in perpendicular directions.
1520 @see: Function L{opposing}.
1521 '''
1522 m = Radians_(margin=margin, low=EPS0, high=PI_2)
1523 return _opposes(radians2 - radians1, m, PI, PI2)
1526def philam2n_xyz(phi, lam, name=NN):
1527 '''Convert lat-, longitude to C{n-vector} (I{normal} to the
1528 earth's surface) X, Y and Z components.
1530 @arg phi: Latitude (C{radians}).
1531 @arg lam: Longitude (C{radians}).
1532 @kwarg name: Optional name (C{str}).
1534 @return: A L{Vector3Tuple}C{(x, y, z)}.
1536 @see: Function L{latlon2n_xyz}.
1538 @note: These are C{n-vector} x, y and z components,
1539 I{NOT} geocentric ECEF x, y and z coordinates!
1540 '''
1541 return _2n_xyz(name, *sincos2_(phi, lam))
1544def _radical2(d, r1, r2): # in .ellipsoidalBaseDI, .sphericalTrigonometry, .vector3d
1545 # (INTERNAL) See C{radical2} below
1546 # assert d > EPS0
1547 r = fsumf_(_1_0, (r1 / d)**2, -(r2 / d)**2) * _0_5
1548 return Radical2Tuple(max(_0_0, min(_1_0, r)), r * d)
1551def radical2(distance, radius1, radius2):
1552 '''Compute the I{radical ratio} and I{radical line} of two
1553 U{intersecting circles<https://MathWorld.Wolfram.com/
1554 Circle-CircleIntersection.html>}.
1556 The I{radical line} is perpendicular to the axis thru the
1557 centers of the circles at C{(0, 0)} and C{(B{distance}, 0)}.
1559 @arg distance: Distance between the circle centers (C{scalar}).
1560 @arg radius1: Radius of the first circle (C{scalar}).
1561 @arg radius2: Radius of the second circle (C{scalar}).
1563 @return: A L{Radical2Tuple}C{(ratio, xline)} where C{0.0 <=
1564 ratio <= 1.0} and C{xline} is along the B{C{distance}}.
1566 @raise IntersectionError: The B{C{distance}} exceeds the sum
1567 of B{C{radius1}} and B{C{radius2}}.
1569 @raise UnitError: Invalid B{C{distance}}, B{C{radius1}} or
1570 B{C{radius2}}.
1572 @see: U{Circle-Circle Intersection
1573 <https://MathWorld.Wolfram.com/Circle-CircleIntersection.html>}.
1574 '''
1575 d = Distance_(distance, low=_0_0)
1576 r1 = Radius_(radius1=radius1)
1577 r2 = Radius_(radius2=radius2)
1578 if d > (r1 + r2):
1579 raise IntersectionError(distance=d, radius1=r1, radius2=r2,
1580 txt=_too_(_distant_))
1581 return _radical2(d, r1, r2) if d > EPS0 else \
1582 Radical2Tuple(_0_5, _0_0)
1585class Radical2Tuple(_NamedTuple):
1586 '''2-Tuple C{(ratio, xline)} of the I{radical} C{ratio} and
1587 I{radical} C{xline}, both C{scalar} and C{0.0 <= ratio <= 1.0}
1588 '''
1589 _Names_ = (_ratio_, _xline_)
1590 _Units_ = ( Scalar, Scalar)
1593def _radistance(inst):
1594 '''(INTERNAL) Helper for the L{frechet._FrecherMeterRadians}
1595 and L{hausdorff._HausdorffMeterRedians} classes.
1596 '''
1597 kwds_ = _xkwds(inst._kwds, wrap=False)
1598 wrap_ = _xkwds_pop(kwds_, wrap=False)
1599 func_ = inst._func_
1600 try: # calling lower-overhead C{func_}
1601 func_(0, _0_25, _0_5, **kwds_)
1602 wrap_ = _Wrap._philamop(wrap_)
1603 except TypeError:
1604 return inst.distance
1606 def _philam(p):
1607 try:
1608 return p.phi, p.lam
1609 except AttributeError: # no .phi or .lam
1610 return radians(p.lat), radians(p.lon)
1612 def _func_wrap(point1, point2):
1613 phi1, lam1 = wrap_(*_philam(point1))
1614 phi2, lam2 = wrap_(*_philam(point2))
1615 return func_(phi2, phi1, lam2 - lam1, **kwds_)
1617 inst._units = inst._units_
1618 return _func_wrap
1621def _scale_deg(lat1, lat2): # degrees
1622 # scale factor cos(mean of lats) for delta lon
1623 m = fabs(lat1 + lat2) * _0_5
1624 return cos(radians(m)) if m < 90 else _0_0
1627def _scale_rad(phi1, phi2): # radians, by .frechet, .hausdorff, .heights
1628 # scale factor cos(mean of phis) for delta lam
1629 m = fabs(phi1 + phi2) * _0_5
1630 return cos(m) if m < PI_2 else _0_0
1633def _sincosa6(phi2, phi1, lam21): # [4] in cosineLaw
1634 '''(INTERNAL) C{sin}es, C{cos}ines and C{acos}ine.
1635 '''
1636 s2, c2, s1, c1, _, c21 = sincos2_(phi2, phi1, lam21)
1637 return s2, c2, s1, c1, acos1(s1 * s2 + c1 * c2 * c21), c21
1640def thomas(lat1, lon1, lat2, lon2, datum=_WGS84, wrap=False):
1641 '''Compute the distance between two (ellipsoidal) points using
1642 U{Thomas'<https://apps.DTIC.mil/dtic/tr/fulltext/u2/703541.pdf>}
1643 formula.
1645 @arg lat1: Start latitude (C{degrees}).
1646 @arg lon1: Start longitude (C{degrees}).
1647 @arg lat2: End latitude (C{degrees}).
1648 @arg lon2: End longitude (C{degrees}).
1649 @kwarg datum: Datum (L{Datum}) or ellipsoid (L{Ellipsoid},
1650 L{Ellipsoid2} or L{a_f2Tuple}) to use.
1651 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll
1652 B{C{lat2}} and B{C{lon2}} (C{bool}).
1654 @return: Distance (C{meter}, same units as the B{C{datum}}'s
1655 ellipsoid axes).
1657 @raise TypeError: Invalid B{C{datum}}.
1659 @see: Functions L{thomas_}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},
1660 L{cosineLaw}, L{equirectangular}, L{euclidean}, L{flatLocal}/L{hubeny},
1661 L{flatPolar}, L{haversine}, L{vincentys} and method L{Ellipsoid.distance2}.
1662 '''
1663 return _dE(thomas_, datum, wrap, lat1, lon1, lat2, lon2)
1666def thomas_(phi2, phi1, lam21, datum=_WGS84):
1667 '''Compute the I{angular} distance between two (ellipsoidal) points using
1668 U{Thomas'<https://apps.DTIC.mil/dtic/tr/fulltext/u2/703541.pdf>}
1669 formula.
1671 @arg phi2: End latitude (C{radians}).
1672 @arg phi1: Start latitude (C{radians}).
1673 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).
1674 @kwarg datum: Datum or ellipsoid to use (L{Datum}, L{Ellipsoid},
1675 L{Ellipsoid2} or L{a_f2Tuple}).
1677 @return: Angular distance (C{radians}).
1679 @raise TypeError: Invalid B{C{datum}}.
1681 @see: Functions L{thomas}, L{cosineAndoyerLambert_},
1682 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},
1683 L{equirectangular_}, L{euclidean_}, L{flatLocal_}/L{hubeny_},
1684 L{flatPolar_}, L{haversine_} and L{vincentys_} and U{Geodesy-PHP
1685 <https://GitHub.com/jtejido/geodesy-php/blob/master/src/Geodesy/
1686 Distance/ThomasFormula.php>}.
1687 '''
1688 s2, c2, s1, c1, r, _ = _sincosa6(phi2, phi1, lam21)
1689 if r and isnon0(c1) and isnon0(c2):
1690 E = _ellipsoidal(datum, thomas_)
1691 if E.f:
1692 r1 = atan2(E.b_a * s1, c1)
1693 r2 = atan2(E.b_a * s2, c2)
1695 j = (r2 + r1) * _0_5
1696 k = (r2 - r1) * _0_5
1697 sj, cj, sk, ck, h, _ = sincos2_(j, k, lam21 * _0_5)
1699 h = fsumf_(sk**2, (ck * h)**2, -(sj * h)**2)
1700 u = _1_0 - h
1701 if isnon0(u) and isnon0(h):
1702 r = atan(sqrt0(h / u)) * 2 # == acos(1 - 2 * h)
1703 sr, cr = sincos2(r)
1704 if isnon0(sr):
1705 u = 2 * (sj * ck)**2 / u
1706 h = 2 * (sk * cj)**2 / h
1707 x = u + h
1708 y = u - h
1710 s = r / sr
1711 e = 4 * s**2
1712 d = 2 * cr
1713 a = e * d
1714 b = 2 * r
1715 c = s - (a - d) * _0_5
1716 f = E.f * _0_25
1718 t = fsumf_(a * x, -b * y, c * x**2, -d * y**2, e * x * y)
1719 r -= fsumf_(s * x, -y, -t * f * _0_25) * f * sr
1720 return r
1723def vincentys(lat1, lon1, lat2, lon2, radius=R_M, wrap=False):
1724 '''Compute the distance between two (spherical) points using
1725 U{Vincenty's<https://WikiPedia.org/wiki/Great-circle_distance>}
1726 spherical formula.
1728 @arg lat1: Start latitude (C{degrees}).
1729 @arg lon1: Start longitude (C{degrees}).
1730 @arg lat2: End latitude (C{degrees}).
1731 @arg lon2: End longitude (C{degrees}).
1732 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum})
1733 or ellipsoid (L{Ellipsoid}, L{Ellipsoid2} or
1734 L{a_f2Tuple}) to use.
1735 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll
1736 B{C{lat2}} and B{C{lon2}} (C{bool}).
1738 @return: Distance (C{meter}, same units as B{C{radius}}).
1740 @raise UnitError: Invalid B{C{radius}}.
1742 @see: Functions L{vincentys_}, L{cosineAndoyerLambert},
1743 L{cosineForsytheAndoyerLambert},L{cosineLaw}, L{equirectangular},
1744 L{euclidean}, L{flatLocal}/L{hubeny}, L{flatPolar},
1745 L{haversine} and L{thomas} and methods L{Ellipsoid.distance2},
1746 C{LatLon.distanceTo*} and C{LatLon.equirectangularTo}.
1748 @note: See note at function L{vincentys_}.
1749 '''
1750 return _dS(vincentys_, radius, wrap, lat1, lon1, lat2, lon2)
1753def vincentys_(phi2, phi1, lam21):
1754 '''Compute the I{angular} distance between two (spherical) points using
1755 U{Vincenty's<https://WikiPedia.org/wiki/Great-circle_distance>}
1756 spherical formula.
1758 @arg phi2: End latitude (C{radians}).
1759 @arg phi1: Start latitude (C{radians}).
1760 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).
1762 @return: Angular distance (C{radians}).
1764 @see: Functions L{vincentys}, L{cosineAndoyerLambert_},
1765 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},
1766 L{equirectangular_}, L{euclidean_}, L{flatLocal_}/L{hubeny_},
1767 L{flatPolar_}, L{haversine_} and L{thomas_}.
1769 @note: Functions L{vincentys_}, L{haversine_} and L{cosineLaw_}
1770 produce equivalent results, but L{vincentys_} is suitable
1771 for antipodal points and slightly more expensive (M{3 cos,
1772 3 sin, 1 hypot, 1 atan2, 6 mul, 2 add}) than L{haversine_}
1773 (M{2 cos, 2 sin, 2 sqrt, 1 atan2, 5 mul, 1 add}) and
1774 L{cosineLaw_} (M{3 cos, 3 sin, 1 acos, 3 mul, 1 add}).
1775 '''
1776 s1, c1, s2, c2, s21, c21 = sincos2_(phi1, phi2, lam21)
1778 c = c2 * c21
1779 x = s1 * s2 + c1 * c
1780 y = c1 * s2 - s1 * c
1781 return atan2(hypot(c2 * s21, y), x)
1783# **) MIT License
1784#
1785# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved.
1786#
1787# Permission is hereby granted, free of charge, to any person obtaining a
1788# copy of this software and associated documentation files (the "Software"),
1789# to deal in the Software without restriction, including without limitation
1790# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1791# and/or sell copies of the Software, and to permit persons to whom the
1792# Software is furnished to do so, subject to the following conditions:
1793#
1794# The above copyright notice and this permission notice shall be included
1795# in all copies or substantial portions of the Software.
1796#
1797# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1798# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1799# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1800# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1801# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1802# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1803# OTHER DEALINGS IN THE SOFTWARE.