Coverage for pygeodesy/latlonBase.py: 93%
473 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'''(INTERNAL) Base class L{LatLonBase} for all elliposiodal, spherical and N-vectorial C{LatLon} classes.
6@see: I{(C) Chris Veness 2005-2024}' U{latlong<https://www.Movable-Type.co.UK/scripts/latlong.html>},
7 U{-ellipsoidal<https://www.Movable-Type.co.UK/scripts/geodesy/docs/latlon-ellipsoidal.js.html>} and
8 U{-vectors<https://www.Movable-Type.co.UK/scripts/latlong-vectors.html>} and I{Charles Karney}'s
9 U{Rhumb<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Rhumb.html>} and
10 U{RhumbLine<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1RhumbLine.html>} classes.
11'''
13from pygeodesy.basics import isstr, map1, _xinstanceof, _passarg
14from pygeodesy.constants import EPS, EPS0, EPS1, EPS4, INT0, R_M, \
15 _EPSqrt as _TOL, _0_0, _0_5, _1_0, \
16 _360_0, _umod_360
17from pygeodesy.datums import _spherical_datum
18from pygeodesy.dms import F_D, F_DMS, latDMS, lonDMS, parse3llh
19# from pygeodesy.ecef import EcefKarney # _MODS
20from pygeodesy.errors import _AttributeError, IntersectionError, \
21 _incompatible, _IsnotError, _TypeError, \
22 _ValueError, _xattr, _xdatum, _xError, \
23 _xkwds, _xkwds_get, _xkwds_item2, _xkwds_not
24# from pygeodesy.fmath import favg # _MODS
25# from pygeodesy.formy import antipode, compassAngle, cosineAndoyerLambert_, \
26# cosineForsytheAndoyerLambert_, cosineLaw, \
27# equirectangular, euclidean, flatLocal_, \
28# flatPolar, _hartzell, haversine, isantipode, \
29# _isequalTo, isnormal, normal, philam2n_xyz, \
30# thomas_, vincentys # as _formy
31# from pygeodesy.internals import _passarg # from .basics
32from pygeodesy.interns import NN, _COMMASPACE_, _concentric_, _height_, \
33 _intersection_, _LatLon_, _m_, _negative_, \
34 _no_, _overlap_, _too_, _point_ # PYCHOK used!
35# from pygeodesy.iters import PointsIter, points2 # _MODS
36# from pygeodesy.karney import Caps # _MODS
37from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS
38from pygeodesy.named import _name2__, _NamedBase, _NamedLocal, Fmt
39from pygeodesy.namedTuples import Bounds2Tuple, LatLon2Tuple, PhiLam2Tuple, \
40 Trilaterate5Tuple, Vector3Tuple
41# from pygeodesy.nvectorBase import _N_vector_ # _MODS
42from pygeodesy.props import deprecated_method, Property, Property_RO, \
43 property_RO, _update_all
44# from pygeodesy.streprs import Fmt, hstr # from .named, _MODS
45from pygeodesy.units import _isDegrees, _isRadius, Distance_, Lat, Lon, \
46 Height, Radius, Radius_, Scalar, Scalar_
47from pygeodesy.utily import sincos2d_, _unrollon, _unrollon3, _Wrap
48# from pygeodesy.vector2d import _circin6, Circin6Tuple, _circum3, circum4_, \
49# Circum3Tuple, _radii11ABC4 # _MODS
50# from pygeodesy.vector3d import nearestOn6, Vector3d # _MODS
52from contextlib import contextmanager
53from math import asin, cos, degrees, fabs, radians
55__all__ = _ALL_LAZY.latlonBase
56__version__ = '24.12.31'
58_formy = _MODS.into(formy=__name__)
61class LatLonBase(_NamedBase, _NamedLocal):
62 '''(INTERNAL) Base class for ellipsoidal and spherical C{LatLon}s.
63 '''
64 _clipid = INT0 # polygonal clip, see .booleans
65 _datum = None # L{Datum}, to be overriden
66 _height = INT0 # height (C{meter}), default
67 _lat = 0 # latitude (C{degrees})
68 _lon = 0 # longitude (C{degrees})
70 def __init__(self, lat_llh, lon=None, height=0, datum=None, **wrap_name):
71 '''New C{LatLon}.
73 @arg lat_llh: Latitude (C{degrees} or DMS C{str} with N or S suffix) or
74 a previous C{LatLon} instance provided C{B{lon}=None}.
75 @kwarg lon: Longitude (C{degrees} or DMS C{str} with E or W suffix),
76 required if B{C{lat_llh}} is C{degrees} or C{str}.
77 @kwarg height: Optional height above (or below) the earth surface
78 (C{meter}, conventionally).
79 @kwarg datum: Optional datum (L{Datum}, L{Ellipsoid}, L{Ellipsoid2},
80 L{a_f2Tuple} or I{scalar} radius) or C{None}.
81 @kwarg wrap_name: Optional C{B{name}=NN} (C{str}) and optional keyword
82 argument C{B{wrap}=False}, if C{True}, wrap or I{normalize}
83 B{C{lat}} and B{C{lon}} (C{bool}).
85 @return: New instance (C{LatLon}).
87 @raise RangeError: A B{C{lon}} or C{lat} value outside the valid
88 range and L{rangerrors} set to C{True}.
90 @raise TypeError: If B{C{lat_llh}} is not a C{LatLon}.
92 @raise UnitError: Invalid C{lat}, B{C{lon}} or B{C{height}}.
93 '''
94 w, n = self._wrap_name2(**wrap_name)
95 if n:
96 self.name = n
98 if lon is None:
99 lat, lon, height = _latlonheight3(lat_llh, height, w)
100 elif w:
101 lat, lon = _Wrap.latlonDMS2(lat_llh, lon)
102 else:
103 lat = lat_llh
105 self._lat = Lat(lat) # parseDMS2(lat, lon)
106 self._lon = Lon(lon) # PYCHOK LatLon2Tuple
107 if height: # elevation
108 self._height = Height(height)
109 if datum is not None:
110 self._datum = _spherical_datum(datum, name=self.name)
112 def __eq__(self, other):
113 return self.isequalTo(other)
115 def __ne__(self, other):
116 return not self.isequalTo(other)
118 def __str__(self):
119 return self.toStr(form=F_D, prec=6)
121 def antipode(self, height=None):
122 '''Return the antipode, the point diametrically opposite to
123 this point.
125 @kwarg height: Optional height of the antipode (C{meter}),
126 this point's height otherwise.
128 @return: The antipodal point (C{LatLon}).
129 '''
130 a = _formy.antipode(*self.latlon)
131 h = self._heigHt(height)
132 return self.classof(*a, height=h)
134 @deprecated_method
135 def bounds(self, wide, tall, radius=R_M): # PYCHOK no cover
136 '''DEPRECATED, use method C{boundsOf}.'''
137 return self.boundsOf(wide, tall, radius=radius)
139 def boundsOf(self, wide, tall, radius=R_M, height=None, **name):
140 '''Return the SW and NE lat-/longitude of a great circle
141 bounding box centered at this location.
143 @arg wide: Longitudinal box width (C{meter}, same units as
144 B{C{radius}} or C{degrees} if C{B{radius} is None}).
145 @arg tall: Latitudinal box size (C{meter}, same units as
146 B{C{radius}} or C{degrees} if C{B{radius} is None}).
147 @kwarg radius: Mean earth radius (C{meter}) or C{None} if I{both}
148 B{C{wide}} and B{C{tall}} are in C{degrees}.
149 @kwarg height: Height for C{latlonSW} and C{latlonNE} (C{meter}),
150 overriding the point's height.
151 @kwarg name: Optional C{B{name}=NN} (C{str}).
153 @return: A L{Bounds2Tuple}C{(latlonSW, latlonNE)}, the lower-left
154 and upper-right corner (C{LatLon}).
156 @see: U{https://www.Movable-Type.co.UK/scripts/latlong-db.html}
157 '''
158 w = Scalar_(wide=wide) * _0_5
159 t = Scalar_(tall=tall) * _0_5
160 if radius is not None:
161 r = Radius_(radius)
162 c = cos(self.phi)
163 w = degrees(asin(w / r) / c) if fabs(c) > EPS0 else _0_0 # XXX
164 t = degrees(t / r)
165 y, t = self.lat, fabs(t)
166 x, w = self.lon, fabs(w)
168 h = self._heigHt(height)
169 sw = self.classof(y - t, x - w, height=h)
170 ne = self.classof(y + t, x + w, height=h)
171 return Bounds2Tuple(sw, ne, name=self._name__(name))
173 def chordTo(self, other, height=None, wrap=False):
174 '''Compute the length of the chord through the earth between
175 this and an other point.
177 @arg other: The other point (C{LatLon}).
178 @kwarg height: Overriding height for both points (C{meter}),
179 or if C{None}, use each point's height.
180 @kwarg wrap: If C{True}, wrap or I{normalize} the B{C{other}}
181 point (C{bool}).
183 @return: The chord length (conventionally C{meter}).
185 @raise TypeError: The B{C{other}} point is not C{LatLon}.
186 '''
187 def _v3d(ll, V3d=_MODS.vector3d.Vector3d):
188 t = ll.toEcef(height=height) # .toVector(Vector=V3d)
189 return V3d(t.x, t.y, t.z)
191 p = self.others(other)
192 if wrap:
193 p = _Wrap.point(p)
194 return _v3d(self).minus(_v3d(p)).length
196 def circin6(self, point2, point3, eps=EPS4, **wrap_name):
197 '''Return the radius and center of the I{inscribed} aka I{In-}circle
198 of the (planar) triangle formed by this and two other points.
200 @arg point2: Second point (C{LatLon}).
201 @arg point3: Third point (C{LatLon}).
202 @kwarg eps: Tolerance for function L{pygeodesy.trilaterate3d2}.
203 @kwarg wrap_name: Optional C{B{name}=NN} (C{str}) and optional keyword
204 argument C{B{wrap}=False}, if C{True}, wrap or I{normalize}
205 the B{C{points}} (C{bool}).
207 @return: A L{Circin6Tuple}C{(radius, center, deltas, cA, cB, cC)}. The
208 C{center} and contact points C{cA}, C{cB} and C{cC}, each an
209 instance of this (sub-)class, are co-planar with this and the
210 two given points, see the B{Note} below.
212 @raise ImportError: Package C{numpy} not found, not installed or older
213 than version 1.10.
215 @raise IntersectionError: Near-coincident or -colinear points or
216 a trilateration or C{numpy} issue.
218 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}.
220 @note: The C{center} is trilaterated in cartesian (ECEF) space and converted
221 back to geodetic lat-, longitude and height. The latter, conventionally
222 in C{meter} indicates whether the C{center} is above, below or on the
223 surface of the earth model. If C{deltas} is C{None}, the C{center} is
224 I{un}ambigous. Otherwise C{deltas} is a L{LatLon3Tuple}C{(lat, lon,
225 height)} representing the differences between both results from
226 L{pygeodesy.trilaterate3d2} and C{center} is the mean thereof.
228 @see: Function L{pygeodesy.circin6}, method L{circum3}, U{Incircle
229 <https://MathWorld.Wolfram.com/Incircle.html>} and U{Contact Triangle
230 <https://MathWorld.Wolfram.com/ContactTriangle.html>}.
231 '''
232 w, n = self._wrap_name2(**wrap_name)
234 with _toCartesian3(self, point2, point3, w) as cs:
235 m = _MODS.vector2d
236 r, c, d, A, B, C = m._circin6(*cs, eps=eps, useZ=True, dLL3=True,
237 datum=self.datum) # PYCHOK unpack
238 return m.Circin6Tuple(r, c.toLatLon(), d, A.toLatLon(),
239 B.toLatLon(),
240 C.toLatLon(), name=n)
242 def circum3(self, point2, point3, circum=True, eps=EPS4, **wrap_name):
243 '''Return the radius and center of the smallest circle I{through} or I{containing}
244 this and two other points.
246 @arg point2: Second point (C{LatLon}).
247 @arg point3: Third point (C{LatLon}).
248 @kwarg circum: If C{True}, return the C{circumradius} and C{circumcenter},
249 always, ignoring the I{Meeus}' Type I case (C{bool}).
250 @kwarg eps: Tolerance for function L{pygeodesy.trilaterate3d2}.
251 @kwarg wrap_name: Optional C{B{name}=NN} (C{str}) and optional keyword
252 argument C{B{wrap}=False}, if C{True}, wrap or I{normalize}
253 the B{C{points}} (C{bool}).
255 @return: A L{Circum3Tuple}C{(radius, center, deltas)}. The C{center}, an
256 instance of this (sub-)class, is co-planar with this and the two
257 given points. If C{deltas} is C{None}, the C{center} is
258 I{un}ambigous. Otherwise C{deltas} is a L{LatLon3Tuple}C{(lat,
259 lon, height)} representing the difference between both results
260 from L{pygeodesy.trilaterate3d2} and C{center} is the mean thereof.
262 @raise ImportError: Package C{numpy} not found, not installed or older than
263 version 1.10.
265 @raise IntersectionError: Near-concentric, -coincident or -colinear points,
266 incompatible C{Ecef} classes or a trilateration
267 or C{numpy} issue.
269 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}.
271 @note: The C{center} is trilaterated in cartesian (ECEF) space and converted
272 back to geodetic lat-, longitude and height. The latter, conventionally
273 in C{meter} indicates whether the C{center} is above, below or on the
274 surface of the earth model. If C{deltas} is C{None}, the C{center} is
275 I{un}ambigous. Otherwise C{deltas} is a L{LatLon3Tuple}C{(lat, lon,
276 height)} representing the difference between both results from
277 L{pygeodesy.trilaterate3d2} and C{center} is the mean thereof.
279 @see: Function L{pygeodesy.circum3} and methods L{circin6} and L{circum4_}.
280 '''
281 w, n = self._wrap_name2(**wrap_name)
283 with _toCartesian3(self, point2, point3, w, circum=circum) as cs:
284 m = _MODS.vector2d
285 r, c, d = m._circum3(*cs, circum=circum, eps=eps, useZ=True, dLL3=True, # XXX -3d2
286 clas=cs[0].classof, datum=self.datum) # PYCHOK unpack
287 return m.Circum3Tuple(r, c.toLatLon(), d, name=n)
289 def circum4_(self, *points, **wrap_name):
290 '''Best-fit a sphere through this and two or more other points.
292 @arg points: The other points (each a C{LatLon}).
293 @kwarg wrap_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument
294 C{B{wrap}=False}, if C{True}, wrap or I{normalize} the B{C{points}}
295 (C{bool}).
297 @return: A L{Circum4Tuple}C{(radius, center, rank, residuals)} with C{center} an
298 instance of this (sub-)class.
300 @raise ImportError: Package C{numpy} not found, not installed or older than
301 version 1.10.
303 @raise NumPyError: Some C{numpy} issue.
305 @raise TypeError: One of the B{C{points}} invalid.
307 @raise ValueError: Too few B{C{points}}.
309 @see: Function L{pygeodesy.circum4_} and L{circum3}.
310 '''
311 w, n = self._wrap_name2(**wrap_name)
313 def _cs(ps, C, w):
314 _wp = _Wrap.point if w else _passarg
315 for i, p in enumerate(ps):
316 yield C(i=i, points=_wp(p))
318 C = self._toCartesianEcef
319 c = C(point=self)
320 t = _MODS.vector2d.circum4_(c, Vector=c.classof, *_cs(points, C, w))
321 c = t.center.toLatLon(LatLon=self.classof)
322 return t.dup(center=c, name=n)
324 @property
325 def clipid(self):
326 '''Get the (polygonal) clip (C{int}).
327 '''
328 return self._clipid
330 @clipid.setter # PYCHOK setter!
331 def clipid(self, clipid):
332 '''Get the (polygonal) clip (C{int}).
333 '''
334 self._clipid = int(clipid)
336 @deprecated_method
337 def compassAngle(self, other, **adjust_wrap): # PYCHOK no cover
338 '''DEPRECATED, use method L{compassAngleTo}.'''
339 return self.compassAngleTo(other, **adjust_wrap)
341 def compassAngleTo(self, other, **adjust_wrap):
342 '''Return the angle from North for the direction vector between
343 this and an other point.
345 Suitable only for short, non-near-polar vectors up to a few
346 hundred Km or Miles. Use method C{initialBearingTo} for
347 larger distances.
349 @arg other: The other point (C{LatLon}).
350 @kwarg adjust_wrap: Optional keyword arguments for function
351 L{pygeodesy.compassAngle}.
353 @return: Compass angle from North (C{degrees360}).
355 @raise TypeError: The B{C{other}} point is not C{LatLon}.
357 @note: Courtesy of Martin Schultz.
359 @see: U{Local, flat earth approximation
360 <https://www.EdWilliams.org/avform.htm#flat>}.
361 '''
362 p = self.others(other)
363 return _formy.compassAngle(self.lat, self.lon, p.lat, p.lon, **adjust_wrap)
365 @deprecated_method
366 def cosineAndoyerLambertTo(self, other, **wrap):
367 '''DEPRECATED on 2024.12.31, use method L{cosineLawTo} with C{B{corr}=1}.'''
368 return self.cosineLawTo(other, corr=1, **wrap)
370 @deprecated_method
371 def cosineForsytheAndoyerLambertTo(self, other, **wrap):
372 '''DEPRECATED on 2024.12.31, use method L{cosineLawTo} with C{B{corr}=2}.'''
373 return self.cosineLawTo(other, corr=2, **wrap)
375 def cosineLawTo(self, other, **radius__corr_wrap):
376 '''Compute the distance between this and an other point using the U{Law of
377 Cosines<https://www.Movable-Type.co.UK/scripts/latlong.html#cosine-law>}
378 formula, optionally corrected.
380 @arg other: The other point (C{LatLon}).
381 @kwarg radius__corr_wrap: Optional earth C{B{radius}=None} (C{meter}),
382 overriding the equatorial or mean radius of this point's
383 datum's ellipsoid and keyword arguments for function
384 L{pygeodesy.cosineLaw}.
386 @return: Distance (C{meter}, same units as B{C{radius}}).
388 @raise TypeError: The B{C{other}} point is not C{LatLon}.
390 @see: Function L{pygeodesy.cosineLaw} and methods C{distanceTo*},
391 L{equirectangularTo}, L{euclideanTo}, L{flatLocalTo} /
392 L{hubenyTo}, L{flatPolarTo}, L{haversineTo}, L{thomasTo} and
393 L{vincentysTo}.
394 '''
395 c = _xkwds_get(radius__corr_wrap, corr=0)
396 return self._distanceTo_(_formy.cosineLaw_, other, **radius__corr_wrap) if c else \
397 self._distanceTo( _formy.cosineLaw, other, **radius__corr_wrap)
399 @property_RO
400 def datum(self): # PYCHOK no cover
401 '''I{Must be overloaded}.'''
402 self._notOverloaded()
404 def destinationXyz(self, delta, LatLon=None, **LatLon_kwds):
405 '''Calculate the destination using a I{local} delta from this point.
407 @arg delta: Local delta to the destination (L{XyzLocal}, L{Aer}, L{Enu}, L{Ned}
408 or L{Local9Tuple}).
409 @kwarg LatLon: Optional (geodetic) class to return the destination or C{None}.
410 @kwarg LatLon_kwds: Optionally, additional B{C{LatLon}} keyword arguments,
411 ignored if C{B{LatLon} is None}.
413 @return: An B{C{LatLon}} instance or if C{B{LatLon} is None}, a
414 L{LatLon4Tuple}C{(lat, lon, height, datum)} or L{LatLon3Tuple}C{(lat,
415 lon, height)} if a C{datum} keyword is specified or not.
417 @raise TypeError: Invalid B{C{delta}}, B{C{LatLon}} or B{C{LatLon_kwds}} item.
418 '''
419 t = self._Ltp._local2ecef(delta, nine=True)
420 return t.toLatLon(LatLon=LatLon, **_xkwds(LatLon_kwds, name=self.name))
422 def _distanceTo(self, func, other, radius=None, **kwds):
423 '''(INTERNAL) Helper for distance methods C{<func>To}.
424 '''
425 p = self.others(other, up=2)
426 R = radius or (self._datum.ellipsoid.R1 if self._datum else R_M)
427 return func(self.lat, self.lon, p.lat, p.lon, radius=R, **kwds)
429 def _distanceTo_(self, func_, other, wrap=False, radius=None, **kwds):
430 '''(INTERNAL) Helper for (ellipsoidal) distance methods C{<func>To}.
431 '''
432 p = self.others(other, up=2)
433 D = self.datum or _spherical_datum(radius or R_M, func_)
434 lam21, phi2, _ = _Wrap.philam3(self.lam, p.phi, p.lam, wrap)
435 r = func_(phi2, self.phi, lam21, datum=D, **kwds)
436 return r * (radius or D.ellipsoid.a)
438 @Property_RO
439 def _Ecef_forward(self):
440 '''(INTERNAL) Helper for L{_ecef9} and L{toEcef} (C{callable}).
441 '''
442 return self.Ecef(self.datum, name=self.name).forward
444 @Property_RO
445 def _ecef9(self):
446 '''(INTERNAL) Helper for L{toCartesian}, L{toEcef} and L{toCartesian} (L{Ecef9Tuple}).
447 '''
448 return self._Ecef_forward(self, M=True)
450 @property_RO
451 def ellipsoidalLatLon(self):
452 '''Get the C{LatLon type} iff ellipsoidal, overloaded in L{LatLonEllipsoidalBase}.
453 '''
454 return False
456 @deprecated_method
457 def equals(self, other, eps=None): # PYCHOK no cover
458 '''DEPRECATED, use method L{isequalTo}.'''
459 return self.isequalTo(other, eps=eps)
461 @deprecated_method
462 def equals3(self, other, eps=None): # PYCHOK no cover
463 '''DEPRECATED, use method L{isequalTo3}.'''
464 return self.isequalTo3(other, eps=eps)
466 def equirectangularTo(self, other, **radius_adjust_limit_wrap):
467 '''Compute the distance between this and an other point
468 using the U{Equirectangular Approximation / Projection
469 <https://www.Movable-Type.co.UK/scripts/latlong.html#equirectangular>}.
471 Suitable only for short, non-near-polar distances up to a
472 few hundred Km or Miles. Use method L{haversineTo} or
473 C{distanceTo*} for more accurate and/or larger distances.
475 @arg other: The other point (C{LatLon}).
476 @kwarg radius_adjust_limit_wrap: Optional keyword arguments
477 for function L{pygeodesy.equirectangular},
478 overriding the default mean C{radius} of this
479 point's datum ellipsoid.
481 @return: Distance (C{meter}, same units as B{C{radius}}).
483 @raise TypeError: The B{C{other}} point is not C{LatLon}.
485 @see: Function L{pygeodesy.equirectangular} and methods L{cosineLawTo},
486 C{distanceTo*}, C{euclideanTo}, L{flatLocalTo} / L{hubenyTo},
487 L{flatPolarTo}, L{haversineTo}, L{thomasTo} and L{vincentysTo}.
488 '''
489 return self._distanceTo(_formy.equirectangular, other, **radius_adjust_limit_wrap)
491 def euclideanTo(self, other, **radius_adjust_wrap):
492 '''Approximate the C{Euclidian} distance between this and
493 an other point.
495 See function L{pygeodesy.euclidean} for the available B{C{options}}.
497 @arg other: The other point (C{LatLon}).
498 @kwarg radius_adjust_wrap: Optional keyword arguments for function
499 L{pygeodesy.euclidean}, overriding the default mean
500 C{radius} of this point's datum ellipsoid.
502 @return: Distance (C{meter}, same units as B{C{radius}}).
504 @raise TypeError: The B{C{other}} point is not C{LatLon}.
506 @see: Function L{pygeodesy.euclidean} and methods L{cosineLawTo}, C{distanceTo*},
507 L{equirectangularTo}, L{flatLocalTo} / L{hubenyTo}, L{flatPolarTo},
508 L{haversineTo}, L{thomasTo} and L{vincentysTo}.
509 '''
510 return self._distanceTo(_formy.euclidean, other, **radius_adjust_wrap)
512 def flatLocalTo(self, other, radius=None, **wrap):
513 '''Compute the distance between this and an other point using the
514 U{ellipsoidal Earth to plane projection
515 <https://WikiPedia.org/wiki/Geographical_distance#Ellipsoidal_Earth_projected_to_a_plane>}
516 aka U{Hubeny<https://www.OVG.AT/de/vgi/files/pdf/3781/>} formula.
518 @arg other: The other point (C{LatLon}).
519 @kwarg radius: Mean earth radius (C{meter}) or C{None} for the I{equatorial
520 radius} of this point's datum ellipsoid.
521 @kwarg wrap: Optional keyword argument C{B{wrap}=False}, if C{True}, wrap
522 or I{normalize} and unroll the B{C{other}} point (C{bool}).
524 @return: Distance (C{meter}, same units as B{C{radius}}).
526 @raise TypeError: The B{C{other}} point is not C{LatLon}.
528 @raise ValueError: Invalid B{C{radius}}.
530 @see: Function L{pygeodesy.flatLocal}/L{pygeodesy.hubeny}, methods L{cosineLawTo},
531 C{distanceTo*}, L{equirectangularTo}, L{euclideanTo}, L{flatPolarTo},
532 L{haversineTo}, L{thomasTo} and L{vincentysTo} and U{local, flat Earth
533 approximation<https://www.edwilliams.org/avform.htm#flat>}.
534 '''
535 r = radius if radius in (None, R_M, _1_0, 1) else Radius(radius)
536 return self._distanceTo_(_formy.flatLocal_, other, radius=r, **wrap) # PYCHOK kwargs
538 hubenyTo = flatLocalTo # for Karl Hubeny
540 def flatPolarTo(self, other, **radius_wrap):
541 '''Compute the distance between this and an other point using
542 the U{polar coordinate flat-Earth<https://WikiPedia.org/wiki/
543 Geographical_distance#Polar_coordinate_flat-Earth_formula>} formula.
545 @arg other: The other point (C{LatLon}).
546 @kwarg radius_wrap: Optional C{B{radius}=R_M} and C{B{wrap}=False} for
547 function L{pygeodesy.flatPolar}, overriding the default
548 C{mean radius} of this point's datum ellipsoid.
550 @return: Distance (C{meter}, same units as B{C{radius}}).
552 @raise TypeError: The B{C{other}} point is not C{LatLon}.
554 @see: Function L{pygeodesy.flatPolar} and methods L{cosineLawTo}, C{distanceTo*},
555 L{equirectangularTo}, L{euclideanTo}, L{flatLocalTo} / L{hubenyTo},
556 L{haversineTo}, L{thomasTo} and L{vincentysTo}.
557 '''
558 return self._distanceTo(_formy.flatPolar, other, **radius_wrap)
560 def hartzell(self, los=False, earth=None):
561 '''Compute the intersection of a Line-Of-Sight from this (geodetic) Point-Of-View
562 (pov) with this point's ellipsoid surface.
564 @kwarg los: Line-Of-Sight, I{direction} to the ellipsoid (L{Los}, L{Vector3d}),
565 C{True} for the I{normal, plumb} onto the surface or I{False} or
566 C{None} to point to the center of the ellipsoid.
567 @kwarg earth: The earth model (L{Datum}, L{Ellipsoid}, L{Ellipsoid2}, L{a_f2Tuple}
568 or C{scalar} radius in C{meter}), overriding this point's C{datum}
569 ellipsoid.
571 @return: The intersection (C{LatLon}) with attribute C{.height} set to the distance
572 to this C{pov}.
574 @raise IntersectionError: Null or bad C{pov} or B{C{los}}, this C{pov} is inside
575 the ellipsoid or B{C{los}} points outside or away from
576 the ellipsoid.
578 @raise TypeError: Invalid B{C{los}} or invalid or undefined B{C{earth}} or C{datum}.
580 @see: Function L{hartzell<pygeodesy.formy.hartzell>} for further details.
581 '''
582 return _formy._hartzell(self, los, earth, LatLon=self.classof)
584 def haversineTo(self, other, **radius_wrap):
585 '''Compute the distance between this and an other point using the U{Haversine
586 <https://www.Movable-Type.co.UK/scripts/latlong.html>} formula.
588 @arg other: The other point (C{LatLon}).
589 @kwarg radius_wrap: Optional C{B{radius}=R_M} and C{B{wrap}=False} for function
590 L{pygeodesy.haversine}, overriding the default C{mean radius} of
591 this point's datum ellipsoid.
593 @return: Distance (C{meter}, same units as B{C{radius}}).
595 @raise TypeError: The B{C{other}} point is not C{LatLon}.
597 @see: Function L{pygeodesy.haversine} and methods L{cosineLawTo}, C{distanceTo*},
598 L{equirectangularTo}, L{euclideanTo}, L{flatLocalTo} / L{hubenyTo}, \
599 L{flatPolarTo}, L{thomasTo} and L{vincentysTo}.
600 '''
601 return self._distanceTo(_formy.haversine, other, **radius_wrap)
603 def _havg(self, other, f=_0_5, h=None):
604 '''(INTERNAL) Weighted, average height.
606 @arg other: An other point (C{LatLon}).
607 @kwarg f: Optional fraction (C{float}).
608 @kwarg h: Overriding height (C{meter}).
610 @return: Average, fractional height (C{float}) or the
611 overriding height B{C{h}} (C{Height}).
612 '''
613 return Height(h) if h is not None else \
614 _MODS.fmath.favg(self.height, other.height, f=f)
616 @Property
617 def height(self):
618 '''Get the height (C{meter}).
619 '''
620 return self._height
622 @height.setter # PYCHOK setter!
623 def height(self, height):
624 '''Set the height (C{meter}).
626 @raise TypeError: Invalid B{C{height}} C{type}.
628 @raise ValueError: Invalid B{C{height}}.
629 '''
630 h = Height(height)
631 if self._height != h:
632 _update_all(self)
633 self._height = h
635 def _heigHt(self, height):
636 '''(INTERNAL) Overriding this C{height}.
637 '''
638 return self.height if height is None else Height(height)
640 def height4(self, earth=None, normal=True, LatLon=None, **LatLon_kwds):
641 '''Compute the projection of this point on and the height above or below
642 this datum's ellipsoid surface.
644 @kwarg earth: A datum, ellipsoid, triaxial ellipsoid or earth radius,
645 I{overriding} this datum (L{Datum}, L{Ellipsoid},
646 L{Ellipsoid2}, L{a_f2Tuple}, L{Triaxial}, L{Triaxial_},
647 L{JacobiConformal} or C{meter}, conventionally).
648 @kwarg normal: If C{True}, the projection is the normal to this ellipsoid's
649 surface, otherwise the intersection of the I{radial} line to
650 this ellipsoid's center (C{bool}).
651 @kwarg LatLon: Optional class to return the projection, height and datum
652 (C{LatLon}) or C{None}.
653 @kwarg LatLon_kwds: Optionally, additional B{C{LatLon}} keyword arguments,
654 ignored if C{B{LatLon} is None}.
656 @note: Use keyword argument C{height=0} to override C{B{LatLon}.height}
657 to {0} or any other C{scalar}, conventionally in C{meter}.
659 @return: A B{C{LatLon}} instance or if C{B{LatLon} is None}, a L{Vector4Tuple}C{(x,
660 y, z, h)} with the I{projection} C{x}, C{y} and C{z} coordinates and
661 height C{h} in C{meter}, conventionally.
663 @raise TriaxialError: No convergence in triaxial root finding.
665 @raise TypeError: Invalid B{C{LatLon}}, B{C{LatLon_kwds}} item, B{C{earth}}
666 or triaxial B{C{earth}} couldn't be converted to biaxial
667 B{C{LatLon}} datum.
669 @see: Methods L{Ellipsoid.height4} and L{Triaxial_.height4} for more information.
670 '''
671 c = self.toCartesian()
672 if LatLon is None:
673 r = c.height4(earth=earth, normal=normal)
674 else:
675 c = c.height4(earth=earth, normal=normal, Cartesian=c.classof, height=0)
676 r = c.toLatLon(LatLon=LatLon, **_xkwds(LatLon_kwds, datum=c.datum, height=c.height))
677 if r.datum != c.datum:
678 raise _TypeError(earth=earth, datum=r.datum)
679 return r
681 def heightStr(self, prec=-2, m=_m_):
682 '''Return this point's B{C{height}} as C{str}ing.
684 @kwarg prec: Number of (decimal) digits, unstripped (C{int}).
685 @kwarg m: Optional unit of the height (C{str}).
687 @see: Function L{pygeodesy.hstr}.
688 '''
689 return _MODS.streprs.hstr(self.height, prec=prec, m=m)
691 def intersecant2(self, *args, **kwds): # PYCHOK no cover
692 '''B{Not implemented}, throws a C{NotImplementedError} always.'''
693 self._notImplemented(*args, **kwds)
695 def _intersecend2(self, p, q, wrap, height, g_or_r, P, Q, unused): # in .LatLonEllipsoidalBaseDI.intersecant2
696 '''(INTERNAL) Interpolate 2 heights along a geodesic or rhumb
697 line and return the 2 intersecant points accordingly.
698 '''
699 if height is None:
700 hp = hq = _xattr(p, height=INT0)
701 h = _xattr(q, height=hp) # if isLatLon(q) else hp
702 if h != hp:
703 s = g_or_r._Inverse(p, q, wrap).s12
704 if s: # fmath.fidw?
705 s = (h - hp) / s # slope
706 hq += s * Q.s12
707 hp += s * P.s12
708 else:
709 hp = hq = _MODS.fmath.favg(hp, h)
710 else:
711 hp = hq = Height(height)
713# n = self.name or unused.__name__
714 p = q = self.classof(P.lat2, P.lon2, datum=g_or_r.datum, height=hp) # name=n
715 p._iteration = P.iteration
716 if P is not Q:
717 q = self.classof(Q.lat2, Q.lon2, datum=g_or_r.datum, height=hq) # name=n
718 q._iteration = Q.iteration
719 return p, q
721 @deprecated_method
722 def isantipode(self, other, eps=EPS): # PYCHOK no cover
723 '''DEPRECATED, use method L{isantipodeTo}.'''
724 return self.isantipodeTo(other, eps=eps)
726 def isantipodeTo(self, other, eps=EPS):
727 '''Check whether this and an other point are antipodal, on diametrically
728 opposite sides of the earth.
730 @arg other: The other point (C{LatLon}).
731 @kwarg eps: Tolerance for near-equality (C{degrees}).
733 @return: C{True} if points are antipodal within the given tolerance,
734 C{False} otherwise.
735 '''
736 p = self.others(other)
737 return _formy.isantipode(*(self.latlon + p.latlon), eps=eps)
739 @Property_RO
740 def isEllipsoidal(self):
741 '''Check whether this point is ellipsoidal (C{bool} or C{None} if unknown).
742 '''
743 return _xattr(self.datum, isEllipsoidal=None)
745 def isequalTo(self, other, eps=None):
746 '''Compare this point with an other point, I{ignoring} height.
748 @arg other: The other point (C{LatLon}).
749 @kwarg eps: Tolerance for equality (C{degrees}).
751 @return: C{True} if both points are identical, I{ignoring} height,
752 C{False} otherwise.
754 @raise TypeError: The B{C{other}} point is not C{LatLon} or mismatch
755 of the B{C{other}} and this C{class} or C{type}.
757 @raise UnitError: Invalid B{C{eps}}.
759 @see: Method L{isequalTo3}.
760 '''
761 return _formy._isequalTo(self, self.others(other), eps=eps)
763 def isequalTo3(self, other, eps=None):
764 '''Compare this point with an other point, I{including} height.
766 @arg other: The other point (C{LatLon}).
767 @kwarg eps: Tolerance for equality (C{degrees}).
769 @return: C{True} if both points are identical I{including} height,
770 C{False} otherwise.
772 @raise TypeError: The B{C{other}} point is not C{LatLon} or mismatch
773 of the B{C{other}} and this C{class} or C{type}.
775 @see: Method L{isequalTo}.
776 '''
777 return self.height == self.others(other).height and \
778 _formy._isequalTo(self, other, eps=eps)
780 @Property_RO
781 def isnormal(self):
782 '''Return C{True} if this point is normal (C{bool}),
783 meaning C{abs(lat) <= 90} and C{abs(lon) <= 180}.
785 @see: Methods L{normal}, L{toNormal} and functions L{isnormal
786 <pygeodesy.isnormal>} and L{normal<pygeodesy.normal>}.
787 '''
788 return _formy.isnormal(self.lat, self.lon, eps=0)
790 @Property_RO
791 def isSpherical(self):
792 '''Check whether this point is spherical (C{bool} or C{None} if unknown).
793 '''
794 return _xattr(self.datum, isSpherical=None)
796 @Property_RO
797 def lam(self):
798 '''Get the longitude (B{C{radians}}).
799 '''
800 return radians(self.lon)
802 @Property
803 def lat(self):
804 '''Get the latitude (C{degrees90}).
805 '''
806 return self._lat
808 @lat.setter # PYCHOK setter!
809 def lat(self, lat):
810 '''Set the latitude (C{str[N|S]} or C{degrees}).
812 @raise ValueError: Invalid B{C{lat}}.
813 '''
814 lat = Lat(lat) # parseDMS(lat, suffix=_NS_, clip=90)
815 if self._lat != lat:
816 _update_all(self)
817 self._lat = lat
819 @Property
820 def latlon(self):
821 '''Get the lat- and longitude (L{LatLon2Tuple}C{(lat, lon)}).
822 '''
823 return LatLon2Tuple(self._lat, self._lon, name=self.name)
825 @latlon.setter # PYCHOK setter!
826 def latlon(self, latlonh):
827 '''Set the lat- and longitude and optionally the height (2- or 3-tuple
828 or comma- or space-separated C{str} of C{degrees90}, C{degrees180}
829 and C{meter}).
831 @raise TypeError: Height of B{C{latlonh}} not C{scalar} or B{C{latlonh}}
832 not C{list} or C{tuple}.
834 @raise ValueError: Invalid B{C{latlonh}} or M{len(latlonh)}.
836 @see: Function L{pygeodesy.parse3llh} to parse a B{C{latlonh}} string
837 into a 3-tuple C{(lat, lon, h)}.
838 '''
839 if isstr(latlonh):
840 latlonh = parse3llh(latlonh, height=self.height)
841 else:
842 _xinstanceof(list, tuple, latlonh=latlonh)
843 if len(latlonh) == 3:
844 h = Height(latlonh[2], name=Fmt.SQUARE(latlonh=2))
845 elif len(latlonh) != 2:
846 raise _ValueError(latlonh=latlonh)
847 else:
848 h = self.height
850 llh = Lat(latlonh[0]), Lon(latlonh[1]), h # parseDMS2(latlonh[0], latlonh[1])
851 if (self._lat, self._lon, self._height) != llh:
852 _update_all(self)
853 self._lat, self._lon, self._height = llh
855 def latlon2(self, ndigits=0):
856 '''Return this point's lat- and longitude in C{degrees}, rounded.
858 @kwarg ndigits: Number of (decimal) digits (C{int}).
860 @return: A L{LatLon2Tuple}C{(lat, lon)}, both C{float} and rounded
861 away from zero.
863 @note: The C{round}ed values are always C{float}, also if B{C{ndigits}}
864 is omitted.
865 '''
866 return LatLon2Tuple(round(self.lat, ndigits),
867 round(self.lon, ndigits), name=self.name)
869 @deprecated_method
870 def latlon_(self, ndigits=0): # PYCHOK no cover
871 '''DEPRECATED, use method L{latlon2}.'''
872 return self.latlon2(ndigits=ndigits)
874 latlon2round = latlon_ # PYCHOK no cover
876 @Property
877 def latlonheight(self):
878 '''Get the lat-, longitude and height (L{LatLon3Tuple}C{(lat, lon, height)}).
879 '''
880 return self.latlon.to3Tuple(self.height)
882 @latlonheight.setter # PYCHOK setter!
883 def latlonheight(self, latlonh):
884 '''Set the lat- and longitude and optionally the height
885 (2- or 3-tuple or comma- or space-separated C{str} of
886 C{degrees90}, C{degrees180} and C{meter}).
888 @see: Property L{latlon} for more details.
889 '''
890 self.latlon = latlonh
892 @Property
893 def lon(self):
894 '''Get the longitude (C{degrees180}).
895 '''
896 return self._lon
898 @lon.setter # PYCHOK setter!
899 def lon(self, lon):
900 '''Set the longitude (C{str[E|W]} or C{degrees}).
902 @raise ValueError: Invalid B{C{lon}}.
903 '''
904 lon = Lon(lon) # parseDMS(lon, suffix=_EW_, clip=180)
905 if self._lon != lon:
906 _update_all(self)
907 self._lon = lon
909 def nearestOn6(self, points, closed=False, height=None, wrap=False):
910 '''Locate the point on a path or polygon closest to this point.
912 Points are converted to and distances are computed in I{geocentric},
913 cartesian space.
915 @arg points: The path or polygon points (C{LatLon}[]).
916 @kwarg closed: Optionally, close the polygon (C{bool}).
917 @kwarg height: Optional height, overriding the height of this and all
918 other points (C{meter}). If C{None}, take the height
919 of points into account for distances.
920 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the B{C{points}}
921 (C{bool}).
923 @return: A L{NearestOn6Tuple}C{(closest, distance, fi, j, start, end)}
924 with the C{closest}, the C{start} and the C{end} point each an
925 instance of this C{LatLon} and C{distance} in C{meter}, same
926 units as the cartesian axes.
928 @raise PointsError: Insufficient number of B{C{points}}.
930 @raise TypeError: Some B{C{points}} or some B{C{points}}' C{Ecef} invalid.
932 @raise ValueError: Some B{C{points}}' C{Ecef} is incompatible.
934 @see: Function L{nearestOn6<pygeodesy.nearestOn6>}.
935 '''
936 def _cs(Ps, h, w, C):
937 p = None # not used
938 for i, q in Ps.enumerate():
939 if w and i:
940 q = _unrollon(p, q)
941 yield C(height=h, i=i, up=3, points=q)
942 p = q
944 C = self._toCartesianEcef # to verify datum and Ecef
945 Ps = self.PointsIter(points, wrap=wrap)
947 c = C(height=height, this=self) # this Cartesian
948 t = _MODS.vector3d.nearestOn6(c, _cs(Ps, height, wrap, C), closed=closed)
949 c, s, e = t.closest, t.start, t.end
951 kwds = _xkwds_not(None, LatLon=self.classof, # this LatLon
952 height=height)
953 _r = self.Ecef(self.datum).reverse
954 p = _r(c).toLatLon(**kwds)
955 s = _r(s).toLatLon(**kwds) if s is not c else p
956 e = _r(e).toLatLon(**kwds) if e is not c else p
957 return t.dup(closest=p, start=s, end=e)
959 def nearestTo(self, *args, **kwds): # PYCHOK no cover
960 '''B{Not implemented}, throws a C{NotImplementedError} always.'''
961 self._notImplemented(*args, **kwds)
963 def normal(self):
964 '''Normalize this point I{in-place} to C{abs(lat) <= 90} and C{abs(lon) <= 180}.
966 @return: C{True} if this point was I{normal}, C{False} if it wasn't (but is now).
968 @see: Property L{isnormal} and method L{toNormal}.
969 '''
970 n = self.isnormal
971 if not n:
972 self.latlon = _formy.normal(*self.latlon)
973 return n
975 @property_RO
976 def _N_vector(self):
977 '''(INTERNAL) Get the C{Nvector} (C{nvectorBase._N_vector_})
978 '''
979 _N = _MODS.nvectorBase._N_vector_
980 return _N(*self._n_xyz3, h=self.height, name=self.name)
982 @Property_RO
983 def _n_xyz3(self):
984 '''(INTERNAL) Get the n-vector components as L{Vector3Tuple}.
985 '''
986 return philam2n_xyz(self.phi, self.lam, name=self.name)
988 @Property_RO
989 def phi(self):
990 '''Get the latitude (B{C{radians}}).
991 '''
992 return radians(self.lat)
994 @Property_RO
995 def philam(self):
996 '''Get the lat- and longitude (L{PhiLam2Tuple}C{(phi, lam)}).
997 '''
998 return PhiLam2Tuple(self.phi, self.lam, name=self.name)
1000 def philam2(self, ndigits=0):
1001 '''Return this point's lat- and longitude in C{radians}, rounded.
1003 @kwarg ndigits: Number of (decimal) digits (C{int}).
1005 @return: A L{PhiLam2Tuple}C{(phi, lam)}, both C{float} and rounded
1006 away from zero.
1008 @note: The C{round}ed values are C{float}, always.
1009 '''
1010 return PhiLam2Tuple(round(self.phi, ndigits),
1011 round(self.lam, ndigits), name=self.name)
1013 @Property_RO
1014 def philamheight(self):
1015 '''Get the lat-, longitude in C{radians} and height (L{PhiLam3Tuple}C{(phi, lam, height)}).
1016 '''
1017 return self.philam.to3Tuple(self.height)
1019 @deprecated_method
1020 def points(self, points, **closed): # PYCHOK no cover
1021 '''DEPRECATED, use method L{points2}.'''
1022 return self.points2(points, **closed)
1024 def points2(self, points, closed=True):
1025 '''Check a path or polygon represented by points.
1027 @arg points: The path or polygon points (C{LatLon}[])
1028 @kwarg closed: Optionally, consider the polygon closed, ignoring any
1029 duplicate or closing final B{C{points}} (C{bool}).
1031 @return: A L{Points2Tuple}C{(number, points)}, an C{int} and a C{list}
1032 or C{tuple}.
1034 @raise PointsError: Insufficient number of B{C{points}}.
1036 @raise TypeError: Some B{C{points}} are not C{LatLon}.
1037 '''
1038 return _MODS.iters.points2(points, closed=closed, base=self)
1040 def PointsIter(self, points, loop=0, dedup=False, wrap=False):
1041 '''Return a C{PointsIter} iterator.
1043 @arg points: The path or polygon points (C{LatLon}[])
1044 @kwarg loop: Number of loop-back points (non-negative C{int}).
1045 @kwarg dedup: If C{True}, skip duplicate points (C{bool}).
1046 @kwarg wrap: If C{True}, wrap or I{normalize} the enum-/iterated
1047 B{C{points}} (C{bool}).
1049 @return: A new C{PointsIter} iterator.
1051 @raise PointsError: Insufficient number of B{C{points}}.
1052 '''
1053 return _MODS.iters.PointsIter(points, base=self, loop=loop,
1054 dedup=dedup, wrap=wrap)
1056 def radii11(self, point2, point3, wrap=False):
1057 '''Return the radii of the C{Circum-}, C{In-}, I{Soddy} and C{Tangent}
1058 circles of a (planar) triangle formed by this and two other points.
1060 @arg point2: Second point (C{LatLon}).
1061 @arg point3: Third point (C{LatLon}).
1062 @kwarg wrap: If C{True}, wrap or I{normalize} B{C{point2}} and
1063 B{C{point3}} (C{bool}).
1065 @return: L{Radii11Tuple}C{(rA, rB, rC, cR, rIn, riS, roS, a, b, c, s)}.
1067 @raise IntersectionError: Near-coincident or -colinear points.
1069 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}.
1071 @see: Function L{pygeodesy.radii11}, U{Incircle
1072 <https://MathWorld.Wolfram.com/Incircle.html>}, U{Soddy Circles
1073 <https://MathWorld.Wolfram.com/SoddyCircles.html>} and U{Tangent
1074 Circles<https://MathWorld.Wolfram.com/TangentCircles.html>}.
1075 '''
1076 with _toCartesian3(self, point2, point3, wrap) as cs:
1077 return _MODS.vector2d._radii11ABC4(*cs, useZ=True)[0]
1079 def _rhumb3(self, exact, radius): # != .sphericalBase._rhumbs3
1080 '''(INTERNAL) Get the C{rhumb} for this point's datum or for
1081 the B{C{radius}}' earth model iff non-C{None}.
1082 '''
1083 try:
1084 d = self._rhumb3dict
1085 t = d[(exact, radius)]
1086 except KeyError:
1087 D = self.datum if radius is None else \
1088 _spherical_datum(radius) # ellipsoidal OK
1089 try:
1090 r = D.ellipsoid.rhumb_(exact=exact) # or D.isSpherical
1091 except AttributeError as x:
1092 raise _AttributeError(datum=D, radius=radius, cause=x)
1093 t = r, D, _MODS.karney.Caps
1094 if len(d) > 2:
1095 d.clear() # d[:] = {}
1096 d[(exact, radius)] = t # cache 3-tuple
1097 return t
1099 @Property_RO
1100 def _rhumb3dict(self): # in ._update
1101 return {} # 3-item cache
1103 def rhumbAzimuthTo(self, other, exact=False, radius=None, wrap=False, b360=False):
1104 '''Return the azimuth (bearing) of a rhumb line (loxodrome) between this and
1105 an other (ellipsoidal) point.
1107 @arg other: The other point (C{LatLon}).
1108 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method
1109 L{Ellipsoid.rhumb_}.
1110 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},
1111 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's datum.
1112 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the B{C{other}} point (C{bool}).
1113 @kwarg b360: If C{True}, return the azimuth as bearing in compass degrees (C{bool}).
1115 @return: Rhumb azimuth (C{degrees180} or compass C{degrees360}).
1117 @raise TypeError: The B{C{other}} point is incompatible or B{C{radius}} is invalid.
1118 '''
1119 r, _, Cs = self._rhumb3(exact, radius)
1120 z = r._Inverse(self, other, wrap, outmask=Cs.AZIMUTH).azi12
1121 return _umod_360(z + _360_0) if b360 else z
1123 def rhumbDestination(self, distance, azimuth, radius=None, height=None, exact=False, **name):
1124 '''Return the destination point having travelled the given distance from this point along
1125 a rhumb line (loxodrome) of the given azimuth.
1127 @arg distance: Distance travelled (C{meter}, same units as this point's datum (ellipsoid)
1128 axes or B{C{radius}}, may be negative.
1129 @arg azimuth: Azimuth (bearing) of the rhumb line (compass C{degrees}).
1130 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},
1131 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's datum.
1132 @kwarg height: Optional height, overriding the default height (C{meter}).
1133 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method L{Ellipsoid.rhumb_}.
1134 @kwarg name: Optional C{B{name}=NN} (C{str}).
1136 @return: The destination point (ellipsoidal C{LatLon}).
1138 @raise TypeError: Invalid B{C{radius}}.
1140 @raise ValueError: Invalid B{C{distance}}, B{C{azimuth}}, B{C{radius}} or B{C{height}}.
1141 '''
1142 r, D, _ = self._rhumb3(exact, radius)
1143 d = r._Direct(self, azimuth, distance)
1144 h = self._heigHt(height)
1145 return self.classof(d.lat2, d.lon2, datum=D, height=h, **name)
1147 def rhumbDistanceTo(self, other, exact=False, radius=None, wrap=False):
1148 '''Return the distance from this to an other point along a rhumb line (loxodrome).
1150 @arg other: The other point (C{LatLon}).
1151 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method L{Ellipsoid.rhumb_}.
1152 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},
1153 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's datum.
1154 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the B{C{other}} point (C{bool}).
1156 @return: Distance (C{meter}, the same units as this point's datum (ellipsoid) axes or B{C{radius}}.
1158 @raise TypeError: The B{C{other}} point is incompatible or B{C{radius}} is invalid.
1160 @raise ValueError: Invalid B{C{radius}}.
1161 '''
1162 r, _, Cs = self._rhumb3(exact, radius)
1163 return r._Inverse(self, other, wrap, outmask=Cs.DISTANCE).s12
1165 def rhumbIntersecant2(self, circle, point, other, height=None,
1166 **exact_radius_wrap_eps_tol):
1167 '''Compute the intersections of a circle and a rhumb line given as two points or as a
1168 point and azimuth.
1170 @arg circle: Radius of the circle centered at this location (C{meter}), or a point
1171 on the circle (same C{LatLon} class).
1172 @arg point: The start point of the rhumb line (same C{LatLon} class).
1173 @arg other: An other point I{on} (same C{LatLon} class) or the azimuth I{of} (compass
1174 C{degrees}) the rhumb line.
1175 @kwarg height: Optional height for the intersection points (C{meter}, conventionally)
1176 or C{None} for interpolated heights.
1177 @kwarg exact_radius_wrap_eps_tol: Optional keyword arguments, see methods L{rhumbLine}
1178 and L{RhumbLineAux.Intersecant2} or L{RhumbLine.Intersecant2}.
1180 @return: 2-Tuple of the intersection points (representing a chord), each an instance of
1181 this class. Both points are the same instance if the rhumb line is tangent to
1182 the circle.
1184 @raise IntersectionError: The circle and rhumb line do not intersect.
1186 @raise TypeError: Invalid B{C{point}}, B{C{circle}} or B{C{other}}.
1188 @raise ValueError: Invalid B{C{circle}}, B{C{other}}, B{C{height}} or B{C{exact_radius_wrap}}.
1190 @see: Methods L{RhumbLineAux.Intersecant2} and L{RhumbLine.Intersecant2}.
1191 '''
1192 def _kwds3(eps=EPS, tol=_TOL, wrap=False, **kwds):
1193 return kwds, wrap, dict(eps=eps, tol=tol)
1195 exact_radius, w, eps_tol = _kwds3(**exact_radius_wrap_eps_tol)
1197 p = _unrollon(self, self.others(point=point), wrap=w)
1198 try:
1199 r = Radius_(circle=circle) if _isRadius(circle) else \
1200 self.rhumbDistanceTo(self.others(circle=circle), wrap=w, **exact_radius)
1201 rl = p.rhumbLine(other, wrap=w, **exact_radius)
1202 P, Q = rl.Intersecant2(self.lat, self.lon, r, **eps_tol)
1204 return self._intersecend2(p, other, w, height, rl.rhumb, P, Q,
1205 self.rhumbIntersecant2)
1206 except (TypeError, ValueError) as x:
1207 raise _xError(x, center=self, circle=circle, point=point, other=other,
1208 **exact_radius_wrap_eps_tol)
1210 def rhumbLine(self, other, exact=False, radius=None, wrap=False, **name_caps):
1211 '''Get a rhumb line through this point at a given azimuth or through this and an other point.
1213 @arg other: The azimuth I{of} (compass C{degrees}) or an other point I{on} (same
1214 C{LatLon} class) the rhumb line.
1215 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method L{Ellipsoid.rhumb_}.
1216 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},
1217 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's C{datum}.
1218 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the B{C{other}} point (C{bool}).
1219 @kwarg name_caps: Optional C{B{name}=str} and C{caps}, see L{RhumbLine} or L{RhumbLineAux} C{B{caps}}.
1221 @return: A C{RhumbLine} instance (C{RhumbLine} or C{RhumbLineAux}).
1223 @raise TypeError: Invalid B{C{radius}} or B{C{other}} not C{scalar} nor same C{LatLon} class.
1225 @see: Modules L{rhumb.aux_} and L{rhumb.ekx}.
1226 '''
1227 r, _, Cs = self._rhumb3(exact, radius)
1228 kwds = _xkwds(name_caps, name=self.name, caps=Cs.LINE_OFF)
1229 rl = r._DirectLine( self, other, **kwds) if _isDegrees(other) else \
1230 r._InverseLine(self, self.others(other), wrap, **kwds)
1231 return rl
1233 def rhumbMidpointTo(self, other, exact=False, radius=None, height=None, fraction=_0_5, **wrap_name):
1234 '''Return the (loxodromic) midpoint on the rhumb line between this and an other point.
1236 @arg other: The other point (same C{LatLon} class).
1237 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method L{Ellipsoid.rhumb_}.
1238 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},
1239 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's datum.
1240 @kwarg height: Optional height, overriding the mean height (C{meter}).
1241 @kwarg fraction: Midpoint location from this point (C{scalar}), 0 for this, 1 for the B{C{other}},
1242 0.5 for halfway between this and the B{C{other}} point, may be negative or
1243 greater than 1.
1244 @kwarg wrap_name: Optional C{B{name}=NN} (C{str}) and C{B{wrap}=False}, if C{True}, wrap or
1245 I{normalize} and unroll the B{C{other}} point (C{bool}).
1247 @return: The midpoint at the given B{C{fraction}} along the rhumb line (same C{LatLon} class).
1249 @raise TypeError: The B{C{other}} point is incompatible or B{C{radius}} is invalid.
1251 @raise ValueError: Invalid B{C{height}} or B{C{fraction}}.
1252 '''
1253 w, n = self._wrap_name2(**wrap_name)
1254 r, D, _ = self._rhumb3(exact, radius)
1255 f = Scalar(fraction=fraction)
1256 d = r._Inverse(self, self.others(other), w) # C.AZIMUTH_DISTANCE
1257 d = r._Direct( self, d.azi12, d.s12 * f)
1258 h = self._havg(other, f=f, h=height)
1259 return self.classof(d.lat2, d.lon2, datum=D, height=h, name=n)
1261 @property_RO
1262 def sphericalLatLon(self):
1263 '''Get the C{LatLon type} iff spherical, overloaded in L{LatLonSphericalBase}.
1264 '''
1265 return False
1267 def thomasTo(self, other, **wrap):
1268 '''Compute the distance between this and an other point using U{Thomas'
1269 <https://apps.DTIC.mil/dtic/tr/fulltext/u2/703541.pdf>} formula.
1271 @arg other: The other point (C{LatLon}).
1272 @kwarg wrap: Optional keyword argument C{B{wrap}=False}, if C{True}, wrap
1273 or I{normalize} and unroll the B{C{other}} point (C{bool}).
1275 @return: Distance (C{meter}, same units as the axes of this point's datum ellipsoid).
1277 @raise TypeError: The B{C{other}} point is not C{LatLon}.
1279 @see: Function L{pygeodesy.thomas} and methods L{cosineLawTo}, C{distanceTo*},
1280 L{equirectangularTo}, L{euclideanTo}, L{flatLocalTo} / L{hubenyTo},
1281 L{flatPolarTo}, L{haversineTo} and L{vincentysTo}.
1282 '''
1283 return self._distanceTo_(_formy.thomas_, other, **wrap)
1285 @deprecated_method
1286 def to2ab(self): # PYCHOK no cover
1287 '''DEPRECATED, use property L{philam}.'''
1288 return self.philam
1290 def toCartesian(self, height=None, Cartesian=None, **Cartesian_kwds):
1291 '''Convert this point to cartesian, I{geocentric} coordinates, also known as
1292 I{Earth-Centered, Earth-Fixed} (ECEF).
1294 @kwarg height: Optional height, overriding this point's height (C{meter},
1295 conventionally).
1296 @kwarg Cartesian: Optional class to return the geocentric coordinates
1297 (C{Cartesian}) or C{None}.
1298 @kwarg Cartesian_kwds: Optionally, additional B{C{Cartesian}} keyword
1299 arguments, ignored if C{B{Cartesian} is None}.
1301 @return: A B{C{Cartesian}} instance or if B{C{Cartesian} is None}, an
1302 L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
1303 C{C=0} and C{M} if available.
1305 @raise TypeError: Invalid B{C{Cartesian}} or B{C{Cartesian_kwds}} item.
1307 @see: Methods C{toNvector}, C{toVector} and C{toVector3d}.
1308 '''
1309 r = self._ecef9 if height is None else self.toEcef(height=height)
1310 if Cartesian is not None: # class or .classof
1311 r = Cartesian(r, **self._name1__(Cartesian_kwds))
1312 _xdatum(r.datum, self.datum)
1313 return r
1315 def _toCartesianEcef(self, height=None, i=None, up=2, **name_point):
1316 '''(INTERNAL) Convert to cartesian and check Ecef's before and after.
1317 '''
1318 p = self.others(up=up, **name_point)
1319 c = p.toCartesian(height=height)
1320 E = self.Ecef
1321 if E:
1322 for p in (p, c):
1323 e = _xattr(p, Ecef=None)
1324 if e not in (None, E): # PYCHOK no cover
1325 n, _ = _xkwds_item2(name_point)
1326 n = Fmt.INDEX(n, i)
1327 raise _ValueError(n, e, txt=_incompatible(E.__name__)) # txt__
1328 return c
1330 def toDatum(self, datum2, height=None, **name):
1331 '''I{Must be overloaded}.'''
1332 self._notOverloaded(datum2, height=height, **name)
1334 def toEcef(self, height=None, M=False):
1335 '''Convert this point to I{geocentric} coordinates, also known as
1336 I{Earth-Centered, Earth-Fixed} (U{ECEF<https://WikiPedia.org/wiki/ECEF>}).
1338 @kwarg height: Optional height, overriding this point's height (C{meter},
1339 conventionally).
1340 @kwarg M: Optionally, include the rotation L{EcefMatrix} (C{bool}).
1342 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
1343 C{C=0} and C{M} if available.
1345 @raise EcefError: A C{.datum} or an ECEF issue.
1346 '''
1347 return self._ecef9 if height in (None, self.height) else \
1348 self._Ecef_forward(self.lat, self.lon, height=height, M=M)
1350 @deprecated_method
1351 def to3llh(self, height=None): # PYCHOK no cover
1352 '''DEPRECATED, use property L{latlonheight} or C{latlon.to3Tuple(B{height})}.'''
1353 return self.latlonheight if height in (None, self.height) else \
1354 self.latlon.to3Tuple(height)
1356 def toNormal(self, deep=False, **name):
1357 '''Get this point I{normalized} to C{abs(lat) <= 90} and C{abs(lon) <= 180}.
1359 @kwarg deep: If C{True}, make a deep, otherwise a shallow copy (C{bool}).
1360 @kwarg name: Optional C{B{name}=NN} (C{str}).
1362 @return: A copy of this point, I{normalized} (C{LatLon}), optionally renamed.
1364 @see: Property L{isnormal}, method L{normal} and function L{pygeodesy.normal}.
1365 '''
1366 ll = self.copy(deep=deep)
1367 _ = ll.normal()
1368 if name:
1369 ll.rename(name)
1370 return ll
1372 def toNvector(self, h=None, Nvector=None, **name_Nvector_kwds):
1373 '''Convert this point to C{n-vector} (normal to the earth's surface) components,
1374 I{including height}.
1376 @kwarg h: Optional height, overriding this point's height (C{meter}).
1377 @kwarg Nvector: Optional class to return the C{n-vector} components (C{Nvector})
1378 or C{None}.
1379 @kwarg name_Nvector_kwds: Optional C{B{name}=NN} (C{str}) and optionally,
1380 additional B{C{Nvector}} keyword arguments, ignored if C{B{Nvector}
1381 is None}.
1383 @return: An B{C{Nvector}} instance or a L{Vector4Tuple}C{(x, y, z, h)} if
1384 C{B{Nvector} is None}.
1386 @raise TypeError: Invalid B{C{h}}, B{C{Nvector}} or B{C{name_Nvector_kwds}}.
1388 @see: Methods C{toCartesian}, C{toVector} and C{toVector3d}.
1389 '''
1390 h = self._heigHt(h)
1391 if Nvector is None:
1392 r = self._n_xyz3.to4Tuple(h)
1393 n, _ = _name2__(name_Nvector_kwds, _or_nameof=self)
1394 if n:
1395 r.rename(n)
1396 else:
1397 x, y, z = self._n_xyz3
1398 r = Nvector(x, y, z, h=h, ll=self, **self._name1__(name_Nvector_kwds))
1399 return r
1401 def toStr(self, form=F_DMS, joined=_COMMASPACE_, m=_m_, **prec_sep_s_D_M_S): # PYCHOK expected
1402 '''Convert this point to a "lat, lon[, +/-height]" string, formatted in the
1403 given C{B{form}at}.
1405 @kwarg form: The lat-/longitude C{B{form}at} to use (C{str}), see functions
1406 L{pygeodesy.latDMS} or L{pygeodesy.lonDMS}.
1407 @kwarg joined: Separator to join the lat-, longitude and height strings (C{str}
1408 or C{None} or C{NN} for non-joined).
1409 @kwarg m: Optional unit of the height (C{str}), use C{None} to exclude height
1410 from the returned string.
1411 @kwarg prec_sep_s_D_M_S: Optional C{B{prec}ision}, C{B{sep}arator}, B{C{s_D}},
1412 B{C{s_M}}, B{C{s_S}} and B{C{s_DMS}} keyword arguments, see function
1413 L{pygeodesy.toDMS} for details.
1415 @return: This point in the specified C{B{form}at}, etc. (C{str} or a 2- or 3-tuple
1416 C{(lat_str, lon_str[, height_str])} if B{C{joined}} is C{NN} or C{None}).
1418 @see: Function L{pygeodesy.latDMS} or L{pygeodesy.lonDMS} for more details about
1419 keyword arguments C{B{form}at}, C{B{prec}ision}, C{B{sep}arator}, B{C{s_D}},
1420 B{C{s_M}}, B{C{s_S}} and B{C{s_DMS}}.
1421 '''
1422 t = (latDMS(self.lat, form=form, **prec_sep_s_D_M_S),
1423 lonDMS(self.lon, form=form, **prec_sep_s_D_M_S))
1424 if self.height and m is not None:
1425 t += (self.heightStr(m=m),)
1426 return joined.join(t) if joined else t
1428 def toVector(self, Vector=None, **Vector_kwds):
1429 '''Convert this point to a C{Vector} with the I{geocentric} C{(x, y, z)} (ECEF)
1430 coordinates, I{ignoring height}.
1432 @kwarg Vector: Optional class to return the I{geocentric} components (L{Vector3d})
1433 or C{None}.
1434 @kwarg Vector_kwds: Optionally, additional B{C{Vector}} keyword arguments,
1435 ignored if C{B{Vector} is None}.
1437 @return: A B{C{Vector}} instance or a L{Vector3Tuple}C{(x, y, z)} if C{B{Vector}
1438 is None}.
1440 @raise TypeError: Invalid B{C{Vector}} or B{C{Vector_kwds}}.
1442 @see: Methods C{toCartesian}, C{toNvector} and C{toVector3d}.
1443 '''
1444 return self._ecef9.toVector(Vector=Vector, **self._name1__(Vector_kwds))
1446 def toVector3d(self, norm=True, **Vector3d_kwds):
1447 '''Convert this point to a L{Vector3d} with the I{geocentric} C{(x, y, z)}
1448 (ECEF) coordinates, I{ignoring height}.
1450 @kwarg norm: If C{False}, don't normalize the coordinates (C{bool}).
1451 @kwarg Vector3d_kwds: Optional L{Vector3d} keyword arguments.
1453 @return: Named, unit vector or vector (L{Vector3d}).
1455 @raise TypeError: Invalid B{C{Vector3d_kwds}}.
1457 @see: Methods C{toCartesian}, C{toNvector} and C{toVector}.
1458 '''
1459 r = self.toVector(Vector=_MODS.vector3d.Vector3d, **Vector3d_kwds)
1460 if norm:
1461 r = r.unit(ll=self)
1462 return r
1464 def toWm(self, **toWm_kwds):
1465 '''Convert this point to a WM coordinate.
1467 @kwarg toWm_kwds: Optional L{pygeodesy.toWm} keyword arguments.
1469 @return: The WM coordinate (L{Wm}).
1471 @see: Function L{pygeodesy.toWm}.
1472 '''
1473 return _MODS.webmercator.toWm(self, **self._name1__(toWm_kwds))
1475 @deprecated_method
1476 def to3xyz(self): # PYCHOK no cover
1477 '''DEPRECATED, use property L{xyz} or method L{toNvector}, L{toVector},
1478 L{toVector3d} or perhaps (geocentric) L{toEcef}.'''
1479 return self.xyz # self.toVector()
1481# def _update(self, updated, *attrs, **setters):
1482# '''(INTERNAL) See C{_NamedBase._update}.
1483# '''
1484# if updated:
1485# self._rhumb3dict.clear()
1486# return _NamedBase._update(self, updated, *attrs, **setters)
1488 def vincentysTo(self, other, **radius_wrap):
1489 '''Compute the distance between this and an other point using U{Vincenty's
1490 <https://WikiPedia.org/wiki/Great-circle_distance>} spherical formula.
1492 @arg other: The other point (C{LatLon}).
1493 @kwarg radius_wrap: Optional C{B{radius}=R_M} and C{B{wrap}=False} for
1494 function L{pygeodesy.vincentys}, overriding the default
1495 C{mean radius} of this point's datum ellipsoid.
1497 @return: Distance (C{meter}, same units as B{C{radius}}).
1499 @raise TypeError: The B{C{other}} point is not C{LatLon}.
1501 @see: Function L{pygeodesy.vincentys} and methods L{cosineLawTo}, C{distanceTo*},
1502 L{equirectangularTo}, L{euclideanTo}, L{flatLocalTo} / L{hubenyTo},
1503 L{flatPolarTo}, L{haversineTo} and L{thomasTo}.
1504 '''
1505 return self._distanceTo(_formy.vincentys, other, **_xkwds(radius_wrap, radius=None))
1507 def _wrap_name2(self, wrap=False, **name):
1508 '''(INTERNAL) Return the C{wrap} and C{name} value.
1509 '''
1510 return wrap, (self._name__(name) if name else NN)
1512 @property_RO
1513 def xyz(self):
1514 '''Get the I{geocentric} C{(x, y, z)} coordinates (L{Vector3Tuple}C{(x, y, z)})
1515 '''
1516 return self._ecef9.xyz
1518 @property_RO
1519 def xyz3(self):
1520 '''Get the I{geocentric} C{(x, y, z)} coordinates as C{3-tuple}.
1521 '''
1522 return tuple(self.xyz)
1524 @Property_RO
1525 def xyzh(self):
1526 '''Get the I{geocentric} C{(x, y, z)} coordinates and height (L{Vector4Tuple}C{(x, y, z, h)})
1527 '''
1528 return self.xyz.to4Tuple(self.height)
1531class _toCartesian3(object): # see also .formy._idllmn6, .geodesicw._wargs, .vector2d._numpy
1532 '''(INTERNAL) Wrapper to convert 2 other points.
1533 '''
1534 @contextmanager # <https://www.Python.org/dev/peps/pep-0343/> Examples
1535 def __call__(self, p, p2, p3, wrap, **kwds):
1536 try:
1537 if wrap:
1538 p2, p3 = map1(_Wrap.point, p2, p3)
1539 kwds = _xkwds(kwds, wrap=wrap)
1540 yield (p. toCartesian().copy(name=_point_), # copy to rename
1541 p._toCartesianEcef(up=4, point2=p2),
1542 p._toCartesianEcef(up=4, point3=p3))
1543 except (AssertionError, TypeError, ValueError) as x: # Exception?
1544 raise _xError(x, point=p, point2=p2, point3=p3, **kwds)
1546_toCartesian3 = _toCartesian3() # PYCHOK singleton
1549def _latlonheight3(latlonh, height, wrap): # in .points.LatLon_.__init__
1550 '''(INTERNAL) Get 3-tuple C{(lat, lon, height)}.
1551 '''
1552 try:
1553 lat, lon = latlonh.lat, latlonh.lon
1554 height = _xattr(latlonh, height=height)
1555 except AttributeError:
1556 raise _IsnotError(_LatLon_, latlonh=latlonh)
1557 if wrap:
1558 lat, lon = _Wrap.latlon(lat, lon)
1559 return lat, lon, height
1562def latlon2n_xyz(lat_ll, lon=None, **name):
1563 '''Convert lat-, longitude to C{n-vector} (I{normal} to the earth's surface) X, Y and Z components.
1565 @arg lat_ll: Latitude (C{degrees}) or a C{LatLon} instance, L{LatLon2Tuple} or other C{LatLon*Tuple}.
1566 @kwarg lon: Longitude (C{degrees}), required if C{B{lon_ll} is degrees}, ignored otherwise.
1567 @kwarg name: Optional C{B{name}=NN} (C{str}).
1569 @return: A L{Vector3Tuple}C{(x, y, z)}.
1571 @see: Function L{philam2n_xyz}.
1573 @note: These are C{n-vector} x, y and z components, I{NOT geocentric} x, y and z (ECEF) coordinates!
1574 '''
1575 lat = lat_ll
1576 if lon is None:
1577 try:
1578 lat, lon = lat_ll.latlon
1579 except AttributeError:
1580 lat = lat_ll.lat
1581 lon = lat_ll.lon
1582 # Kenneth Gade eqn 3, but using right-handed
1583 # vector x -> 0°E,0°N, y -> 90°E,0°N, z -> 90°N
1584 sa, ca, sb, cb = sincos2d_(lat, lon)
1585 return Vector3Tuple(ca * cb, ca * sb, sa, **name)
1588def philam2n_xyz(phi_ll, lam=None, **name):
1589 '''Convert lat-, longitude to C{n-vector} (I{normal} to the earth's surface) X, Y and Z components.
1591 @arg phi_ll: Latitude (C{radians}) or a C{LatLon} instance with C{phi}, C{lam} or C{philam} attributes.
1592 @kwarg lam: Longitude (C{radians}), required if C{B{phi_ll} is radians}, ignored otherwise.
1593 @kwarg name: Optional name (C{str}).
1595 @return: A L{Vector3Tuple}C{(x, y, z)}.
1597 @see: Function L{latlon2n_xyz}.
1599 @note: These are C{n-vector} x, y and z components, I{NOT geocentric} x, y and z (ECEF) coordinates!
1600 '''
1601 phi = phi_ll
1602 if lam is None:
1603 try:
1604 phi, lam = phi_ll.philam
1605 except AttributeError:
1606 phi = phi_ll.phi
1607 lam = phi_ll.lam
1608 return latlon2n_xyz(degrees(phi), degrees(lam), **name)
1611def _trilaterate5(p1, d1, p2, d2, p3, d3, area=True, eps=EPS1, radius=R_M, wrap=False): # MCCABE 13
1612 '''(INTERNAL) Trilaterate three points by I{area overlap} or by I{perimeter intersection} of three circles.
1614 @note: The B{C{radius}} is needed only for C{n-vectorial} and C{sphericalTrigonometry.LatLon.distanceTo}
1615 methods and silently ignored by the C{ellipsoidalExact}, C{-GeodSolve}, C{-Karney} and
1616 C{-Vincenty.LatLon.distanceTo} methods.
1617 '''
1618 p2, p3, w = _unrollon3(p1, p2, p3, wrap)
1619 rw = dict(radius=radius, wrap=w)
1621 r1 = Distance_(distance1=d1)
1622 r2 = Distance_(distance2=d2)
1623 r3 = Distance_(distance3=d3)
1624 m = 0 if area else (r1 + r2 + r3)
1625 pc = 0
1626 t = []
1627 for _ in range(3):
1628 try: # intersection of circle (p1, r1) and (p2, r2)
1629 c1, c2 = p1.intersections2(r1, p2, r2, wrap=w)
1631 if area: # check overlap
1632 if c1 is c2: # abutting
1633 c = c1
1634 else: # nearest point on radical
1635 c = p3.nearestOn(c1, c2, within=True, wrap=w)
1636 d = r3 - p3.distanceTo(c, **rw)
1637 if d > eps: # sufficient overlap
1638 t.append((d, c))
1639 m = max(m, d)
1641 else: # check intersection
1642 for c in ((c1,) if c1 is c2 else (c1, c2)):
1643 d = fabs(r3 - p3.distanceTo(c, **rw))
1644 if d < eps: # below margin
1645 t.append((d, c))
1646 m = min(m, d)
1648 except IntersectionError as x:
1649 if _concentric_ in str(x): # XXX ConcentricError?
1650 pc += 1
1652 p1, r1, p2, r2, p3, r3 = p2, r2, p3, r3, p1, r1 # rotate
1654 if t: # get min, max, points and count ...
1655 t = tuple(sorted(t))
1656 n = len(t), # as 1-tuple
1657 # ... or for a single trilaterated result,
1658 # min *is* max, min- *is* maxPoint and n=1, 2 or 3
1659 return Trilaterate5Tuple(t[0] + t[-1] + n) # *(t[0] + ...)
1661 elif area and pc == 3: # all pairwise concentric ...
1662 r, p = min((r1, p1), (r2, p2), (r3, p3))
1663 m = max(r1, r2, r3)
1664 # ... return "smallest" point twice, the smallest
1665 # and largest distance and n=0 for concentric
1666 return Trilaterate5Tuple(float(r), p, float(m), p, 0)
1668 n, f = (_overlap_, max) if area else (_intersection_, min)
1669 t = _COMMASPACE_(_no_(n), '%s %.3g' % (f.__name__, m))
1670 raise IntersectionError(area=area, eps=eps, wrap=wrap, txt=t)
1673__all__ += _ALL_DOCS(LatLonBase)
1675# **) MIT License
1676#
1677# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved.
1678#
1679# Permission is hereby granted, free of charge, to any person obtaining a
1680# copy of this software and associated documentation files (the "Software"),
1681# to deal in the Software without restriction, including without limitation
1682# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1683# and/or sell copies of the Software, and to permit persons to whom the
1684# Software is furnished to do so, subject to the following conditions:
1685#
1686# The above copyright notice and this permission notice shall be included
1687# in all copies or substantial portions of the Software.
1688#
1689# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1690# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1691# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1692# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1693# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1694# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1695# OTHER DEALINGS IN THE SOFTWARE.