Coverage for pygeodesy/latlonBase.py: 93%
475 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-05-29 12:40 -0400
« prev ^ index » next coverage.py v7.6.1, created at 2025-05-29 12:40 -0400
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 _isin, isstr, map1, _xinstanceof
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.ecefLocals import _EcefLocal
21from pygeodesy.errors import _AttributeError, IntersectionError, \
22 _incompatible, _IsnotError, _TypeError, \
23 _ValueError, _xattr, _xdatum, _xError, \
24 _xkwds, _xkwds_get, _xkwds_item2, _xkwds_not
25# from pygeodesy.fmath import favg # _MODS
26# from pygeodesy import formy as _formy # _MODS.into
27from pygeodesy.internals import _passarg, typename
28from pygeodesy.interns import NN, _COMMASPACE_, _concentric_, _intersection_, \
29 _LatLon_, _m_, _no_, _overlap_, _point_ # PYCHOK used!
30# from pygeodesy.iters import PointsIter, points2 # _MODS
31# from pygeodesy.karney import Caps # _MODS
32from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS
33from pygeodesy.named import _name2__, _NamedBase, Fmt
34from pygeodesy.namedTuples import Bounds2Tuple, LatLon2Tuple, PhiLam2Tuple, \
35 Trilaterate5Tuple, Vector3Tuple
36# from pygeodesy.nvectorBase import _N_vector_ # _MODS
37from pygeodesy.props import deprecated_method, Property, Property_RO, \
38 property_RO, _update_all
39# from pygeodesy.streprs import Fmt, hstr # from .named, _MODS
40from pygeodesy.units import _isDegrees, _isRadius, Distance_, Lat, Lon, \
41 Height, Radius, Radius_, Scalar, Scalar_
42from pygeodesy.utily import sincos2d_, _unrollon, _unrollon3, _Wrap
43# from pygeodesy.vector2d import _circin6, Circin6Tuple, _circum3, circum4_, \
44# Circum3Tuple, _radii11ABC4 # _MODS
45# from pygeodesy.vector3d import nearestOn6, Vector3d # _MODS
47from contextlib import contextmanager
48from math import asin, cos, degrees, fabs, radians
50__all__ = _ALL_LAZY.latlonBase
51__version__ = '25.05.07'
53_formy = _MODS.into(formy=__name__)
56class LatLonBase(_NamedBase, _EcefLocal):
57 '''(INTERNAL) Base class for ellipsoidal and spherical C{satLon}s.
58 '''
59 _clipid = INT0 # polygonal clip, see .booleans
60 _datum = None # L{Datum}, to be overriden
61 _height = INT0 # height (C{meter}), default
62 _lat = 0 # latitude (C{degrees})
63 _lon = 0 # longitude (C{degrees})
65 def __init__(self, lat_llh, lon=None, height=0, datum=None, **wrap_name):
66 '''New C{LatLon}.
68 @arg lat_llh: Latitude (C{degrees} or DMS C{str} with N or S suffix) or
69 a previous C{LatLon} instance provided C{B{lon}=None}.
70 @kwarg lon: Longitude (C{degrees} or DMS C{str} with E or W suffix),
71 required if B{C{lat_llh}} is C{degrees} or C{str}.
72 @kwarg height: Optional height above (or below) the earth surface
73 (C{meter}, conventionally).
74 @kwarg datum: Optional datum (L{Datum}, L{Ellipsoid}, L{Ellipsoid2},
75 L{a_f2Tuple} or I{scalar} radius) or C{None}.
76 @kwarg wrap_name: Optional C{B{name}=NN} (C{str}) and optional keyword
77 argument C{B{wrap}=False}, if C{True}, wrap or I{normalize}
78 B{C{lat}} and B{C{lon}} (C{bool}).
80 @return: New instance (C{LatLon}).
82 @raise RangeError: A B{C{lon}} or C{lat} value outside the valid
83 range and L{rangerrors} set to C{True}.
85 @raise TypeError: If B{C{lat_llh}} is not a C{LatLon}.
87 @raise UnitError: Invalid C{lat}, B{C{lon}} or B{C{height}}.
88 '''
89 w, n = self._wrap_name2(**wrap_name)
90 if n:
91 self.name = n
93 if lon is None:
94 lat, lon, height = _latlonheight3(lat_llh, height, w)
95 elif w:
96 lat, lon = _Wrap.latlonDMS2(lat_llh, lon)
97 else:
98 lat = lat_llh
100 self._lat = Lat(lat) # parseDMS2(lat, lon)
101 self._lon = Lon(lon) # PYCHOK LatLon2Tuple
102 if height: # elevation
103 self._height = Height(height)
104 if datum is not None:
105 self._datum = _spherical_datum(datum, name=self.name)
107 def __eq__(self, other):
108 return self.isequalTo(other)
110 def __ne__(self, other):
111 return not self.isequalTo(other)
113 def __str__(self):
114 return self.toStr(form=F_D, prec=6)
116 def antipode(self, height=None):
117 '''Return the antipode, the point diametrically opposite to
118 this point.
120 @kwarg height: Optional height of the antipode (C{meter}),
121 this point's height otherwise.
123 @return: The antipodal point (C{LatLon}).
124 '''
125 a = _formy.antipode(*self.latlon)
126 h = self._heigHt(height)
127 return self.classof(*a, height=h)
129 @deprecated_method
130 def bounds(self, wide, tall, radius=R_M): # PYCHOK no cover
131 '''DEPRECATED, use method C{boundsOf}.'''
132 return self.boundsOf(wide, tall, radius=radius)
134 def boundsOf(self, wide, tall, radius=R_M, height=None, **name):
135 '''Return the SW and NE lat-/longitude of a great circle
136 bounding box centered at this location.
138 @arg wide: Longitudinal box width (C{meter}, same units as
139 B{C{radius}} or C{degrees} if C{B{radius} is None}).
140 @arg tall: Latitudinal box size (C{meter}, same units as
141 B{C{radius}} or C{degrees} if C{B{radius} is None}).
142 @kwarg radius: Mean earth radius (C{meter}) or C{None} if I{both}
143 B{C{wide}} and B{C{tall}} are in C{degrees}.
144 @kwarg height: Height for C{latlonSW} and C{latlonNE} (C{meter}),
145 overriding the point's height.
146 @kwarg name: Optional C{B{name}=NN} (C{str}).
148 @return: A L{Bounds2Tuple}C{(latlonSW, latlonNE)}, the lower-left
149 and upper-right corner (C{LatLon}).
151 @see: U{https://www.Movable-Type.co.UK/scripts/latlong-db.html}
152 '''
153 w = Scalar_(wide=wide) * _0_5
154 t = Scalar_(tall=tall) * _0_5
155 if radius is not None:
156 r = Radius_(radius)
157 c = cos(self.phi)
158 w = degrees(asin(w / r) / c) if fabs(c) > EPS0 else _0_0 # XXX
159 t = degrees(t / r)
160 y, t = self.lat, fabs(t)
161 x, w = self.lon, fabs(w)
163 h = self._heigHt(height)
164 sw = self.classof(y - t, x - w, height=h)
165 ne = self.classof(y + t, x + w, height=h)
166 return Bounds2Tuple(sw, ne, name=self._name__(name))
168 def chordTo(self, other, height=None, wrap=False):
169 '''Compute the length of the chord through the earth between
170 this and an other point.
172 @arg other: The other point (C{LatLon}).
173 @kwarg height: Overriding height for both points (C{meter}),
174 or if C{None}, use each point's height.
175 @kwarg wrap: If C{True}, wrap or I{normalize} the B{C{other}}
176 point (C{bool}).
178 @return: The chord length (conventionally C{meter}).
180 @raise TypeError: The B{C{other}} point is not C{LatLon}.
181 '''
182 def _v3d(ll, V3d=_MODS.vector3d.Vector3d):
183 t = ll.toEcef(height=height) # .toVector(Vector=V3d)
184 return V3d(t.x, t.y, t.z)
186 p = self.others(other)
187 if wrap:
188 p = _Wrap.point(p)
189 return _v3d(self).minus(_v3d(p)).length
191 def circin6(self, point2, point3, eps=EPS4, **wrap_name):
192 '''Return the radius and center of the I{inscribed} aka I{In-}circle
193 of the (planar) triangle formed by this and two other points.
195 @arg point2: Second point (C{LatLon}).
196 @arg point3: Third point (C{LatLon}).
197 @kwarg eps: Tolerance for function L{pygeodesy.trilaterate3d2}.
198 @kwarg wrap_name: Optional C{B{name}=NN} (C{str}) and optional keyword
199 argument C{B{wrap}=False}, if C{True}, wrap or I{normalize}
200 the B{C{points}} (C{bool}).
202 @return: A L{Circin6Tuple}C{(radius, center, deltas, cA, cB, cC)}. The
203 C{center} and contact points C{cA}, C{cB} and C{cC}, each an
204 instance of this (sub-)class, are co-planar with this and the
205 two given points, see the B{Note} below.
207 @raise ImportError: Package C{numpy} not found, not installed or older
208 than version 1.10.
210 @raise IntersectionError: Near-coincident or -colinear points or
211 a trilateration or C{numpy} issue.
213 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}.
215 @note: The C{center} is trilaterated in cartesian (ECEF) space and converted
216 back to geodetic lat-, longitude and height. The latter, conventionally
217 in C{meter} indicates whether the C{center} is above, below or on the
218 surface of the earth model. If C{deltas} is C{None}, the C{center} is
219 I{un}ambigous. Otherwise C{deltas} is a L{LatLon3Tuple}C{(lat, lon,
220 height)} representing the differences between both results from
221 L{pygeodesy.trilaterate3d2} and C{center} is the mean thereof.
223 @see: Function L{pygeodesy.circin6}, method L{circum3}, U{Incircle
224 <https://MathWorld.Wolfram.com/Incircle.html>} and U{Contact Triangle
225 <https://MathWorld.Wolfram.com/ContactTriangle.html>}.
226 '''
227 w, n = self._wrap_name2(**wrap_name)
229 with _toCartesian3(self, point2, point3, w) as cs:
230 m = _MODS.vector2d
231 r, c, d, A, B, C = m._circin6(*cs, eps=eps, useZ=True, dLL3=True,
232 datum=self.datum) # PYCHOK unpack
233 return m.Circin6Tuple(r, c.toLatLon(), d, A.toLatLon(),
234 B.toLatLon(),
235 C.toLatLon(), name=n)
237 def circum3(self, point2, point3, circum=True, eps=EPS4, **wrap_name):
238 '''Return the radius and center of the smallest circle I{through} or I{containing}
239 this and two other points.
241 @arg point2: Second point (C{LatLon}).
242 @arg point3: Third point (C{LatLon}).
243 @kwarg circum: If C{True}, return the C{circumradius} and C{circumcenter},
244 always, ignoring the I{Meeus}' Type I case (C{bool}).
245 @kwarg eps: Tolerance for function L{pygeodesy.trilaterate3d2}.
246 @kwarg wrap_name: Optional C{B{name}=NN} (C{str}) and optional keyword
247 argument C{B{wrap}=False}, if C{True}, wrap or I{normalize}
248 the B{C{points}} (C{bool}).
250 @return: A L{Circum3Tuple}C{(radius, center, deltas)}. The C{center}, an
251 instance of this (sub-)class, is co-planar with this and the two
252 given points. If C{deltas} is C{None}, the C{center} is
253 I{un}ambigous. Otherwise C{deltas} is a L{LatLon3Tuple}C{(lat,
254 lon, height)} representing the difference between both results
255 from L{pygeodesy.trilaterate3d2} and C{center} is the mean thereof.
257 @raise ImportError: Package C{numpy} not found, not installed or older than
258 version 1.10.
260 @raise IntersectionError: Near-concentric, -coincident or -colinear points,
261 incompatible C{Ecef} classes or a trilateration
262 or C{numpy} issue.
264 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}.
266 @note: The C{center} is trilaterated in cartesian (ECEF) space and converted
267 back to geodetic lat-, longitude and height. The latter, conventionally
268 in C{meter} indicates whether the C{center} is above, below or on the
269 surface of the earth model. If C{deltas} is C{None}, the C{center} is
270 I{un}ambigous. Otherwise C{deltas} is a L{LatLon3Tuple}C{(lat, lon,
271 height)} representing the difference between both results from
272 L{pygeodesy.trilaterate3d2} and C{center} is the mean thereof.
274 @see: Function L{pygeodesy.circum3} and methods L{circin6} and L{circum4_}.
275 '''
276 w, n = self._wrap_name2(**wrap_name)
278 with _toCartesian3(self, point2, point3, w, circum=circum) as cs:
279 m = _MODS.vector2d
280 r, c, d = m._circum3(*cs, circum=circum, eps=eps, useZ=True, dLL3=True, # XXX -3d2
281 clas=cs[0].classof, datum=self.datum) # PYCHOK unpack
282 return m.Circum3Tuple(r, c.toLatLon(), d, name=n)
284 def circum4_(self, *points, **wrap_name):
285 '''Best-fit a sphere through this and two or more other points.
287 @arg points: The other points (each a C{LatLon}).
288 @kwarg wrap_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument
289 C{B{wrap}=False}, if C{True}, wrap or I{normalize} the B{C{points}}
290 (C{bool}).
292 @return: A L{Circum4Tuple}C{(radius, center, rank, residuals)} with C{center} an
293 instance of this (sub-)class.
295 @raise ImportError: Package C{numpy} not found, not installed or older than
296 version 1.10.
298 @raise NumPyError: Some C{numpy} issue.
300 @raise TypeError: One of the B{C{points}} invalid.
302 @raise ValueError: Too few B{C{points}}.
304 @see: Function L{pygeodesy.circum4_} and L{circum3}.
305 '''
306 w, n = self._wrap_name2(**wrap_name)
308 def _cs(ps, C, w):
309 _wp = _Wrap.point if w else _passarg
310 for i, p in enumerate(ps):
311 yield C(i=i, points=_wp(p))
313 C = self._toCartesianEcef
314 c = C(point=self)
315 t = _MODS.vector2d.circum4_(c, Vector=c.classof, *_cs(points, C, w))
316 c = t.center.toLatLon(LatLon=self.classof)
317 return t.dup(center=c, name=n)
319 @property
320 def clipid(self):
321 '''Get the (polygonal) clip (C{int}).
322 '''
323 return self._clipid
325 @clipid.setter # PYCHOK setter!
326 def clipid(self, clipid):
327 '''Get the (polygonal) clip (C{int}).
328 '''
329 self._clipid = int(clipid)
331 @deprecated_method
332 def compassAngle(self, other, **adjust_wrap): # PYCHOK no cover
333 '''DEPRECATED, use method L{compassAngleTo}.'''
334 return self.compassAngleTo(other, **adjust_wrap)
336 def compassAngleTo(self, other, **adjust_wrap):
337 '''Return the angle from North for the direction vector between
338 this and an other point.
340 Suitable only for short, non-near-polar vectors up to a few
341 hundred Km or Miles. Use method C{initialBearingTo} for
342 larger distances.
344 @arg other: The other point (C{LatLon}).
345 @kwarg adjust_wrap: Optional keyword arguments for function
346 L{pygeodesy.compassAngle}.
348 @return: Compass angle from North (C{degrees360}).
350 @raise TypeError: The B{C{other}} point is not C{LatLon}.
352 @note: Courtesy of Martin Schultz.
354 @see: U{Local, flat earth approximation
355 <https://www.EdWilliams.org/avform.htm#flat>}.
356 '''
357 p = self.others(other)
358 return _formy.compassAngle(self.lat, self.lon, p.lat, p.lon, **adjust_wrap)
360 @deprecated_method
361 def cosineAndoyerLambertTo(self, other, **wrap):
362 '''DEPRECATED on 2024.12.31, use method L{cosineLawTo} with C{B{corr}=1}.'''
363 return self.cosineLawTo(other, corr=1, **wrap)
365 @deprecated_method
366 def cosineForsytheAndoyerLambertTo(self, other, **wrap):
367 '''DEPRECATED on 2024.12.31, use method L{cosineLawTo} with C{B{corr}=2}.'''
368 return self.cosineLawTo(other, corr=2, **wrap)
370 def cosineLawTo(self, other, **radius__corr_wrap):
371 '''Compute the distance between this and an other point using the U{Law of
372 Cosines<https://www.Movable-Type.co.UK/scripts/latlong.html#cosine-law>}
373 formula, optionally corrected.
375 @arg other: The other point (C{LatLon}).
376 @kwarg radius__corr_wrap: Optional earth C{B{radius}=None} (C{meter}),
377 overriding the equatorial or mean radius of this point's
378 datum's ellipsoid and keyword arguments for function
379 L{pygeodesy.cosineLaw}.
381 @return: Distance (C{meter}, same units as B{C{radius}}).
383 @raise TypeError: The B{C{other}} point is not C{LatLon}.
385 @see: Function L{pygeodesy.cosineLaw} and methods C{distanceTo*},
386 L{equirectangularTo}, L{euclideanTo}, L{flatLocalTo} /
387 L{hubenyTo}, L{flatPolarTo}, L{haversineTo}, L{thomasTo} and
388 L{vincentysTo}.
389 '''
390 c = _xkwds_get(radius__corr_wrap, corr=0)
391 return self._distanceTo_(_formy.cosineLaw_, other, **radius__corr_wrap) if c else \
392 self._distanceTo( _formy.cosineLaw, other, **radius__corr_wrap)
394 @property_RO
395 def datum(self): # PYCHOK no cover
396 '''I{Must be overloaded}.'''
397 self._notOverloaded()
399 def destinationXyz(self, delta, LatLon=None, **LatLon_kwds):
400 '''Calculate the destination using a I{local} delta from this point.
402 @arg delta: Local delta to the destination (L{XyzLocal}, L{Aer}, L{Enu}, L{Ned}
403 or L{Local9Tuple}).
404 @kwarg LatLon: Optional (geodetic) class to return the destination or C{None}.
405 @kwarg LatLon_kwds: Optionally, additional B{C{LatLon}} keyword arguments,
406 ignored if C{B{LatLon} is None}.
408 @return: An B{C{LatLon}} instance or if C{B{LatLon} is None}, a
409 L{LatLon4Tuple}C{(lat, lon, height, datum)} or L{LatLon3Tuple}C{(lat,
410 lon, height)} if a C{datum} keyword is specified or not.
412 @raise TypeError: Invalid B{C{delta}}, B{C{LatLon}} or B{C{LatLon_kwds}} item.
413 '''
414 t = self._ltp._local2ecef(delta, nine=True) # _EcefLocal._ltp
415 return t.toLatLon(LatLon=LatLon, **_xkwds(LatLon_kwds, name=self.name))
417 def _distanceTo(self, func, other, radius=None, **kwds):
418 '''(INTERNAL) Helper for distance methods C{<func>To}.
419 '''
420 p = self.others(other, up=2)
421 R = radius or (self._datum.ellipsoid.R1 if self._datum else R_M)
422 return func(self.lat, self.lon, p.lat, p.lon, radius=R, **kwds)
424 def _distanceTo_(self, func_, other, wrap=False, radius=None, **kwds):
425 '''(INTERNAL) Helper for (ellipsoidal) distance methods C{<func>To}.
426 '''
427 p = self.others(other, up=2)
428 D = self.datum or _spherical_datum(radius or R_M, func_)
429 lam21, phi2, _ = _Wrap.philam3(self.lam, p.phi, p.lam, wrap)
430 r = func_(phi2, self.phi, lam21, datum=D, **kwds)
431 return r * (radius or D.ellipsoid.a)
433 @Property_RO
434 def _Ecef_forward(self):
435 '''(INTERNAL) Helper for L{_ecef9} and L{toEcef} (C{callable}).
436 '''
437 return self.Ecef(self.datum, name=self.name).forward
439 @Property_RO
440 def _ecef9(self):
441 '''(INTERNAL) Helper for L{toCartesian}, L{toEcef} and L{toCartesian} (L{Ecef9Tuple}).
442 '''
443 return self._Ecef_forward(self, M=True)
445 @property_RO
446 def ellipsoidalLatLon(self):
447 '''Get the C{LatLon type} iff ellipsoidal, overloaded in L{LatLonEllipsoidalBase}.
448 '''
449 return False
451 @deprecated_method
452 def equals(self, other, eps=None): # PYCHOK no cover
453 '''DEPRECATED, use method L{isequalTo}.'''
454 return self.isequalTo(other, eps=eps)
456 @deprecated_method
457 def equals3(self, other, eps=None): # PYCHOK no cover
458 '''DEPRECATED, use method L{isequalTo3}.'''
459 return self.isequalTo3(other, eps=eps)
461 def equirectangularTo(self, other, **radius_adjust_limit_wrap):
462 '''Compute the distance between this and an other point
463 using the U{Equirectangular Approximation / Projection
464 <https://www.Movable-Type.co.UK/scripts/latlong.html#equirectangular>}.
466 Suitable only for short, non-near-polar distances up to a
467 few hundred Km or Miles. Use method L{haversineTo} or
468 C{distanceTo*} for more accurate and/or larger distances.
470 @arg other: The other point (C{LatLon}).
471 @kwarg radius_adjust_limit_wrap: Optional keyword arguments
472 for function L{pygeodesy.equirectangular},
473 overriding the default mean C{radius} of this
474 point's datum ellipsoid.
476 @return: Distance (C{meter}, same units as B{C{radius}}).
478 @raise TypeError: The B{C{other}} point is not C{LatLon}.
480 @see: Function L{pygeodesy.equirectangular} and methods L{cosineLawTo},
481 C{distanceTo*}, C{euclideanTo}, L{flatLocalTo} / L{hubenyTo},
482 L{flatPolarTo}, L{haversineTo}, L{thomasTo} and L{vincentysTo}.
483 '''
484 return self._distanceTo(_formy.equirectangular, other, **radius_adjust_limit_wrap)
486 def euclideanTo(self, other, **radius_adjust_wrap):
487 '''Approximate the C{Euclidian} distance between this and
488 an other point.
490 See function L{pygeodesy.euclidean} for the available B{C{options}}.
492 @arg other: The other point (C{LatLon}).
493 @kwarg radius_adjust_wrap: Optional keyword arguments for function
494 L{pygeodesy.euclidean}, overriding the default mean
495 C{radius} of this point's datum ellipsoid.
497 @return: Distance (C{meter}, same units as B{C{radius}}).
499 @raise TypeError: The B{C{other}} point is not C{LatLon}.
501 @see: Function L{pygeodesy.euclidean} and methods L{cosineLawTo}, C{distanceTo*},
502 L{equirectangularTo}, L{flatLocalTo} / L{hubenyTo}, L{flatPolarTo},
503 L{haversineTo}, L{thomasTo} and L{vincentysTo}.
504 '''
505 return self._distanceTo(_formy.euclidean, other, **radius_adjust_wrap)
507 def flatLocalTo(self, other, radius=None, **wrap):
508 '''Compute the distance between this and an other point using the
509 U{ellipsoidal Earth to plane projection
510 <https://WikiPedia.org/wiki/Geographical_distance#Ellipsoidal_Earth_projected_to_a_plane>}
511 aka U{Hubeny<https://www.OVG.AT/de/vgi/files/pdf/3781/>} formula.
513 @arg other: The other point (C{LatLon}).
514 @kwarg radius: Mean earth radius (C{meter}) or C{None} for the I{equatorial
515 radius} of this point's datum ellipsoid.
516 @kwarg wrap: Optional keyword argument C{B{wrap}=False}, if C{True}, wrap
517 or I{normalize} and unroll the B{C{other}} point (C{bool}).
519 @return: Distance (C{meter}, same units as B{C{radius}}).
521 @raise TypeError: The B{C{other}} point is not C{LatLon}.
523 @raise ValueError: Invalid B{C{radius}}.
525 @see: Function L{pygeodesy.flatLocal}/L{pygeodesy.hubeny}, methods L{cosineLawTo},
526 C{distanceTo*}, L{equirectangularTo}, L{euclideanTo}, L{flatPolarTo},
527 L{haversineTo}, L{thomasTo} and L{vincentysTo} and U{local, flat Earth
528 approximation<https://www.edwilliams.org/avform.htm#flat>}.
529 '''
530 r = radius if _isin(radius, None, R_M, _1_0, 1) else Radius(radius)
531 return self._distanceTo_(_formy.flatLocal_, other, radius=r, **wrap) # PYCHOK kwargs
533 hubenyTo = flatLocalTo # for Karl Hubeny
535 def flatPolarTo(self, other, **radius_wrap):
536 '''Compute the distance between this and an other point using
537 the U{polar coordinate flat-Earth<https://WikiPedia.org/wiki/
538 Geographical_distance#Polar_coordinate_flat-Earth_formula>} formula.
540 @arg other: The other point (C{LatLon}).
541 @kwarg radius_wrap: Optional C{B{radius}=R_M} and C{B{wrap}=False} for
542 function L{pygeodesy.flatPolar}, overriding the default
543 C{mean radius} of this point's datum ellipsoid.
545 @return: Distance (C{meter}, same units as B{C{radius}}).
547 @raise TypeError: The B{C{other}} point is not C{LatLon}.
549 @see: Function L{pygeodesy.flatPolar} and methods L{cosineLawTo}, C{distanceTo*},
550 L{equirectangularTo}, L{euclideanTo}, L{flatLocalTo} / L{hubenyTo},
551 L{haversineTo}, L{thomasTo} and L{vincentysTo}.
552 '''
553 return self._distanceTo(_formy.flatPolar, other, **radius_wrap)
555 def hartzell(self, los=False, earth=None):
556 '''Compute the intersection of a Line-Of-Sight from this (geodetic) Point-Of-View
557 (pov) with this point's ellipsoid surface.
559 @kwarg los: Line-Of-Sight, I{direction} to the ellipsoid (L{Los}, L{Vector3d}),
560 C{True} for the I{normal, plumb} onto the surface or I{False} or
561 C{None} to point to the center of the ellipsoid.
562 @kwarg earth: The earth model (L{Datum}, L{Ellipsoid}, L{Ellipsoid2}, L{a_f2Tuple}
563 or C{scalar} radius in C{meter}), overriding this point's C{datum}
564 ellipsoid.
566 @return: The intersection (C{LatLon}) with attribute C{.height} set to the distance
567 to this C{pov}.
569 @raise IntersectionError: Null or bad C{pov} or B{C{los}}, this C{pov} is inside
570 the ellipsoid or B{C{los}} points outside or away from
571 the ellipsoid.
573 @raise TypeError: Invalid B{C{los}} or invalid or undefined B{C{earth}} or C{datum}.
575 @see: Function L{hartzell<pygeodesy.formy.hartzell>} for further details.
576 '''
577 return _formy._hartzell(self, los, earth, LatLon=self.classof)
579 def haversineTo(self, other, **radius_wrap):
580 '''Compute the distance between this and an other point using the U{Haversine
581 <https://www.Movable-Type.co.UK/scripts/latlong.html>} formula.
583 @arg other: The other point (C{LatLon}).
584 @kwarg radius_wrap: Optional C{B{radius}=R_M} and C{B{wrap}=False} for function
585 L{pygeodesy.haversine}, overriding the default C{mean radius} of
586 this point's datum ellipsoid.
588 @return: Distance (C{meter}, same units as B{C{radius}}).
590 @raise TypeError: The B{C{other}} point is not C{LatLon}.
592 @see: Function L{pygeodesy.haversine} and methods L{cosineLawTo}, C{distanceTo*},
593 L{equirectangularTo}, L{euclideanTo}, L{flatLocalTo} / L{hubenyTo}, \
594 L{flatPolarTo}, L{thomasTo} and L{vincentysTo}.
595 '''
596 return self._distanceTo(_formy.haversine, other, **radius_wrap)
598 def _havg(self, other, f=_0_5, h=None):
599 '''(INTERNAL) Weighted, average height.
601 @arg other: An other point (C{LatLon}).
602 @kwarg f: Optional fraction (C{float}).
603 @kwarg h: Overriding height (C{meter}).
605 @return: Average, fractional height (C{float}) or the
606 overriding height B{C{h}} (C{Height}).
607 '''
608 return Height(h) if h is not None else \
609 _MODS.fmath.favg(self.height, other.height, f=f)
611 @Property
612 def height(self):
613 '''Get the height (C{meter}).
614 '''
615 return self._height
617 @height.setter # PYCHOK setter!
618 def height(self, height):
619 '''Set the height (C{meter}).
621 @raise TypeError: Invalid B{C{height}} C{type}.
623 @raise ValueError: Invalid B{C{height}}.
624 '''
625 h = Height(height)
626 if self._height != h:
627 _update_all(self)
628 self._height = h
630 def _heigHt(self, height):
631 '''(INTERNAL) Overriding this C{height}.
632 '''
633 return self.height if height is None else Height(height)
635 def height4(self, earth=None, normal=True, LatLon=None, **LatLon_kwds):
636 '''Compute the projection of this point on and the height above or below
637 this datum's ellipsoid surface.
639 @kwarg earth: A datum, ellipsoid, triaxial ellipsoid or earth radius,
640 I{overriding} this datum (L{Datum}, L{Ellipsoid},
641 L{Ellipsoid2}, L{a_f2Tuple}, L{Triaxial}, L{Triaxial_},
642 L{JacobiConformal} or C{meter}, conventionally).
643 @kwarg normal: If C{True}, the projection is the normal to this ellipsoid's
644 surface, otherwise the intersection of the I{radial} line to
645 this ellipsoid's center (C{bool}).
646 @kwarg LatLon: Optional class to return the projection, height and datum
647 (C{LatLon}) or C{None}.
648 @kwarg LatLon_kwds: Optionally, additional B{C{LatLon}} keyword arguments,
649 ignored if C{B{LatLon} is None}.
651 @note: Use keyword argument C{height=0} to override C{B{LatLon}.height}
652 to {0} or any other C{scalar}, conventionally in C{meter}.
654 @return: A B{C{LatLon}} instance or if C{B{LatLon} is None}, a L{Vector4Tuple}C{(x,
655 y, z, h)} with the I{projection} C{x}, C{y} and C{z} coordinates and
656 height C{h} in C{meter}, conventionally.
658 @raise TriaxialError: No convergence in triaxial root finding.
660 @raise TypeError: Invalid B{C{LatLon}}, B{C{LatLon_kwds}} item, B{C{earth}}
661 or triaxial B{C{earth}} couldn't be converted to biaxial
662 B{C{LatLon}} datum.
664 @see: Methods L{Ellipsoid.height4} and L{Triaxial_.height4} for more information.
665 '''
666 c = self.toCartesian()
667 if LatLon is None:
668 r = c.height4(earth=earth, normal=normal)
669 else:
670 c = c.height4(earth=earth, normal=normal, Cartesian=c.classof, height=0)
671 r = c.toLatLon(LatLon=LatLon, **_xkwds(LatLon_kwds, datum=c.datum, height=c.height))
672 if r.datum != c.datum:
673 raise _TypeError(earth=earth, datum=r.datum)
674 return r
676 def heightStr(self, prec=-2, m=_m_):
677 '''Return this point's B{C{height}} as C{str}ing.
679 @kwarg prec: Number of (decimal) digits, unstripped (C{int}).
680 @kwarg m: Optional unit of the height (C{str}).
682 @see: Function L{pygeodesy.hstr}.
683 '''
684 return _MODS.streprs.hstr(self.height, prec=prec, m=m)
686 def intersecant2(self, *args, **kwds): # PYCHOK no cover
687 '''B{Not implemented}, throws a C{NotImplementedError} always.'''
688 self._notImplemented(*args, **kwds)
690 def _intersecend2(self, p, q, wrap, height, g_or_r, P, Q, unused): # in .LatLonEllipsoidalBaseDI.intersecant2
691 '''(INTERNAL) Interpolate 2 heights along a geodesic or rhumb
692 line and return the 2 intersecant points accordingly.
693 '''
694 if height is None:
695 hp = hq = _xattr(p, height=INT0)
696 h = _xattr(q, height=hp) # if isLatLon(q) else hp
697 if h != hp:
698 s = g_or_r._Inverse(p, q, wrap).s12
699 if s: # fmath.fidw?
700 s = (h - hp) / s # slope
701 hq += s * Q.s12
702 hp += s * P.s12
703 else:
704 hp = hq = _MODS.fmath.favg(hp, h)
705 else:
706 hp = hq = Height(height)
708# n = self.name or typename(unused)
709 p = q = self.classof(P.lat2, P.lon2, datum=g_or_r.datum, height=hp) # name=n
710 p._iteration = P.iteration
711 if P is not Q:
712 q = self.classof(Q.lat2, Q.lon2, datum=g_or_r.datum, height=hq) # name=n
713 q._iteration = Q.iteration
714 return p, q
716 @deprecated_method
717 def isantipode(self, other, eps=EPS): # PYCHOK no cover
718 '''DEPRECATED, use method L{isantipodeTo}.'''
719 return self.isantipodeTo(other, eps=eps)
721 def isantipodeTo(self, other, eps=EPS):
722 '''Check whether this and an other point are antipodal, on diametrically
723 opposite sides of the earth.
725 @arg other: The other point (C{LatLon}).
726 @kwarg eps: Tolerance for near-equality (C{degrees}).
728 @return: C{True} if points are antipodal within the given tolerance,
729 C{False} otherwise.
730 '''
731 p = self.others(other)
732 return _formy.isantipode(*(self.latlon + p.latlon), eps=eps)
734 @Property_RO
735 def isEllipsoidal(self):
736 '''Check whether this point is ellipsoidal (C{bool} or C{None} if unknown).
737 '''
738 return _xattr(self.datum, isEllipsoidal=None)
740 def isequalTo(self, other, eps=None):
741 '''Compare this point with an other point, I{ignoring} height.
743 @arg other: The other point (C{LatLon}).
744 @kwarg eps: Tolerance for equality (C{degrees}).
746 @return: C{True} if both points are identical, I{ignoring} height,
747 C{False} otherwise.
749 @raise TypeError: The B{C{other}} point is not C{LatLon} or mismatch
750 of the B{C{other}} and this C{class} or C{type}.
752 @raise UnitError: Invalid B{C{eps}}.
754 @see: Method L{isequalTo3}.
755 '''
756 return _formy._isequalTo(self, self.others(other), eps=eps)
758 def isequalTo3(self, other, eps=None):
759 '''Compare this point with an other point, I{including} height.
761 @arg other: The other point (C{LatLon}).
762 @kwarg eps: Tolerance for equality (C{degrees}).
764 @return: C{True} if both points are identical I{including} height,
765 C{False} otherwise.
767 @raise TypeError: The B{C{other}} point is not C{LatLon} or mismatch
768 of the B{C{other}} and this C{class} or C{type}.
770 @see: Method L{isequalTo}.
771 '''
772 return self.height == self.others(other).height and \
773 _formy._isequalTo(self, other, eps=eps)
775 @Property_RO
776 def isnormal(self):
777 '''Return C{True} if this point is normal (C{bool}),
778 meaning C{abs(lat) <= 90} and C{abs(lon) <= 180}.
780 @see: Methods L{normal}, L{toNormal} and functions L{isnormal
781 <pygeodesy.isnormal>} and L{normal<pygeodesy.normal>}.
782 '''
783 return _formy.isnormal(self.lat, self.lon, eps=0)
785 @Property_RO
786 def isSpherical(self):
787 '''Check whether this point is spherical (C{bool} or C{None} if unknown).
788 '''
789 return _xattr(self.datum, isSpherical=None)
791 @Property_RO
792 def lam(self):
793 '''Get the longitude (B{C{radians}}).
794 '''
795 return radians(self.lon)
797 @Property
798 def lat(self):
799 '''Get the latitude (C{degrees90}).
800 '''
801 return self._lat
803 @lat.setter # PYCHOK setter!
804 def lat(self, lat):
805 '''Set the latitude (C{str[N|S]} or C{degrees}).
807 @raise ValueError: Invalid B{C{lat}}.
808 '''
809 lat = Lat(lat) # parseDMS(lat, suffix=_NS_, clip=90)
810 if self._lat != lat:
811 _update_all(self)
812 self._lat = lat
814 @Property
815 def latlon(self):
816 '''Get the lat- and longitude (L{LatLon2Tuple}C{(lat, lon)}).
817 '''
818 return LatLon2Tuple(self._lat, self._lon, name=self.name)
820 @latlon.setter # PYCHOK setter!
821 def latlon(self, latlonh):
822 '''Set the lat- and longitude and optionally the height (2- or 3-tuple
823 or comma- or space-separated C{str} of C{degrees90}, C{degrees180}
824 and C{meter}).
826 @raise TypeError: Height of B{C{latlonh}} not C{scalar} or B{C{latlonh}}
827 not C{list} or C{tuple}.
829 @raise ValueError: Invalid B{C{latlonh}} or M{len(latlonh)}.
831 @see: Function L{pygeodesy.parse3llh} to parse a B{C{latlonh}} string
832 into a 3-tuple C{(lat, lon, h)}.
833 '''
834 if isstr(latlonh):
835 latlonh = parse3llh(latlonh, height=self.height)
836 else:
837 _xinstanceof(list, tuple, latlonh=latlonh)
838 if len(latlonh) == 3:
839 h = Height(latlonh[2], name=Fmt.SQUARE(latlonh=2))
840 elif len(latlonh) != 2:
841 raise _ValueError(latlonh=latlonh)
842 else:
843 h = self.height
845 llh = Lat(latlonh[0]), Lon(latlonh[1]), h # parseDMS2(latlonh[0], latlonh[1])
846 if (self._lat, self._lon, self._height) != llh:
847 _update_all(self)
848 self._lat, self._lon, self._height = llh
850 def latlon2(self, ndigits=0):
851 '''Return this point's lat- and longitude in C{degrees}, rounded.
853 @kwarg ndigits: Number of (decimal) digits (C{int}).
855 @return: A L{LatLon2Tuple}C{(lat, lon)}, both C{float} and rounded
856 away from zero.
858 @note: The C{round}ed values are always C{float}, also if B{C{ndigits}}
859 is omitted.
860 '''
861 return LatLon2Tuple(round(self.lat, ndigits),
862 round(self.lon, ndigits), name=self.name)
864 @deprecated_method
865 def latlon_(self, ndigits=0): # PYCHOK no cover
866 '''DEPRECATED, use method L{latlon2}.'''
867 return self.latlon2(ndigits=ndigits)
869 latlon2round = latlon_ # PYCHOK no cover
871 @Property
872 def latlonheight(self):
873 '''Get the lat-, longitude and height (L{LatLon3Tuple}C{(lat, lon, height)}).
874 '''
875 return self.latlon.to3Tuple(self.height)
877 @latlonheight.setter # PYCHOK setter!
878 def latlonheight(self, latlonh):
879 '''Set the lat- and longitude and optionally the height
880 (2- or 3-tuple or comma- or space-separated C{str} of
881 C{degrees90}, C{degrees180} and C{meter}).
883 @see: Property L{latlon} for more details.
884 '''
885 self.latlon = latlonh
887 @Property
888 def lon(self):
889 '''Get the longitude (C{degrees180}).
890 '''
891 return self._lon
893 @lon.setter # PYCHOK setter!
894 def lon(self, lon):
895 '''Set the longitude (C{str[E|W]} or C{degrees}).
897 @raise ValueError: Invalid B{C{lon}}.
898 '''
899 lon = Lon(lon) # parseDMS(lon, suffix=_EW_, clip=180)
900 if self._lon != lon:
901 _update_all(self)
902 self._lon = lon
904# _ltp = _EcefLocal._ltp(self)
906 def nearestOn6(self, points, closed=False, height=None, wrap=False):
907 '''Locate the point on a path or polygon closest to this point.
909 Points are converted to and distances are computed in I{geocentric},
910 cartesian space.
912 @arg points: The path or polygon points (C{LatLon}[]).
913 @kwarg closed: Optionally, close the polygon (C{bool}).
914 @kwarg height: Optional height, overriding the height of this and all
915 other points (C{meter}). If C{None}, take the height
916 of points into account for distances.
917 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the B{C{points}}
918 (C{bool}).
920 @return: A L{NearestOn6Tuple}C{(closest, distance, fi, j, start, end)}
921 with the C{closest}, the C{start} and the C{end} point each an
922 instance of this C{LatLon} and C{distance} in C{meter}, same
923 units as the cartesian axes.
925 @raise PointsError: Insufficient number of B{C{points}}.
927 @raise TypeError: Some B{C{points}} or some B{C{points}}' C{Ecef} invalid.
929 @raise ValueError: Some B{C{points}}' C{Ecef} is incompatible.
931 @see: Function L{nearestOn6<pygeodesy.nearestOn6>}.
932 '''
933 def _cs(Ps, h, w, C):
934 p = None # not used
935 for i, q in Ps.enumerate():
936 if w and i:
937 q = _unrollon(p, q)
938 yield C(height=h, i=i, up=3, points=q)
939 p = q
941 C = self._toCartesianEcef # to verify datum and Ecef
942 Ps = self.PointsIter(points, wrap=wrap)
944 c = C(height=height, this=self) # this Cartesian
945 t = _MODS.vector3d.nearestOn6(c, _cs(Ps, height, wrap, C), closed=closed)
946 c, s, e = t.closest, t.start, t.end
948 kwds = _xkwds_not(None, LatLon=self.classof, # this LatLon
949 height=height)
950 _r = self.Ecef(self.datum).reverse
951 p = _r(c).toLatLon(**kwds)
952 s = _r(s).toLatLon(**kwds) if s is not c else p
953 e = _r(e).toLatLon(**kwds) if e is not c else p
954 return t.dup(closest=p, start=s, end=e)
956 def nearestTo(self, *args, **kwds): # PYCHOK no cover
957 '''B{Not implemented}, throws a C{NotImplementedError} always.'''
958 self._notImplemented(*args, **kwds)
960 def normal(self):
961 '''Normalize this point I{in-place} to C{abs(lat) <= 90} and C{abs(lon) <= 180}.
963 @return: C{True} if this point was I{normal}, C{False} if it wasn't (but is now).
965 @see: Property L{isnormal} and method L{toNormal}.
966 '''
967 n = self.isnormal
968 if not n:
969 self.latlon = _formy.normal(*self.latlon)
970 return n
972 @property_RO
973 def _N_vector(self):
974 '''(INTERNAL) Get the C{Nvector} (C{nvectorBase._N_vector_})
975 '''
976 _N = _MODS.nvectorBase._N_vector_
977 return _N(*self._n_xyz3, h=self.height, name=self.name)
979 @Property_RO
980 def _n_xyz3(self):
981 '''(INTERNAL) Get the n-vector components as L{Vector3Tuple}.
982 '''
983 return philam2n_xyz(self.phi, self.lam, name=self.name)
985 @Property_RO
986 def phi(self):
987 '''Get the latitude (B{C{radians}}).
988 '''
989 return radians(self.lat)
991 @Property_RO
992 def philam(self):
993 '''Get the lat- and longitude (L{PhiLam2Tuple}C{(phi, lam)}).
994 '''
995 return PhiLam2Tuple(self.phi, self.lam, name=self.name)
997 def philam2(self, ndigits=0):
998 '''Return this point's lat- and longitude in C{radians}, rounded.
1000 @kwarg ndigits: Number of (decimal) digits (C{int}).
1002 @return: A L{PhiLam2Tuple}C{(phi, lam)}, both C{float} and rounded
1003 away from zero.
1005 @note: The C{round}ed values are C{float}, always.
1006 '''
1007 return PhiLam2Tuple(round(self.phi, ndigits),
1008 round(self.lam, ndigits), name=self.name)
1010 @Property_RO
1011 def philamheight(self):
1012 '''Get the lat-, longitude in C{radians} and height (L{PhiLam3Tuple}C{(phi, lam, height)}).
1013 '''
1014 return self.philam.to3Tuple(self.height)
1016 @deprecated_method
1017 def points(self, points, **closed): # PYCHOK no cover
1018 '''DEPRECATED, use method L{points2}.'''
1019 return self.points2(points, **closed)
1021 def points2(self, points, closed=True):
1022 '''Check a path or polygon represented by points.
1024 @arg points: The path or polygon points (C{LatLon}[])
1025 @kwarg closed: Optionally, consider the polygon closed, ignoring any
1026 duplicate or closing final B{C{points}} (C{bool}).
1028 @return: A L{Points2Tuple}C{(number, points)}, an C{int} and a C{list}
1029 or C{tuple}.
1031 @raise PointsError: Insufficient number of B{C{points}}.
1033 @raise TypeError: Some B{C{points}} are not C{LatLon}.
1034 '''
1035 return _MODS.iters.points2(points, closed=closed, base=self)
1037 def PointsIter(self, points, loop=0, dedup=False, wrap=False):
1038 '''Return a C{PointsIter} iterator.
1040 @arg points: The path or polygon points (C{LatLon}[])
1041 @kwarg loop: Number of loop-back points (non-negative C{int}).
1042 @kwarg dedup: If C{True}, skip duplicate points (C{bool}).
1043 @kwarg wrap: If C{True}, wrap or I{normalize} the enum-/iterated
1044 B{C{points}} (C{bool}).
1046 @return: A new C{PointsIter} iterator.
1048 @raise PointsError: Insufficient number of B{C{points}}.
1049 '''
1050 return _MODS.iters.PointsIter(points, base=self, loop=loop,
1051 dedup=dedup, wrap=wrap)
1053 def radii11(self, point2, point3, wrap=False):
1054 '''Return the radii of the C{Circum-}, C{In-}, I{Soddy} and C{Tangent}
1055 circles of a (planar) triangle formed by this and two other points.
1057 @arg point2: Second point (C{LatLon}).
1058 @arg point3: Third point (C{LatLon}).
1059 @kwarg wrap: If C{True}, wrap or I{normalize} B{C{point2}} and
1060 B{C{point3}} (C{bool}).
1062 @return: L{Radii11Tuple}C{(rA, rB, rC, cR, rIn, riS, roS, a, b, c, s)}.
1064 @raise IntersectionError: Near-coincident or -colinear points.
1066 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}.
1068 @see: Function L{pygeodesy.radii11}, U{Incircle
1069 <https://MathWorld.Wolfram.com/Incircle.html>}, U{Soddy Circles
1070 <https://MathWorld.Wolfram.com/SoddyCircles.html>} and U{Tangent
1071 Circles<https://MathWorld.Wolfram.com/TangentCircles.html>}.
1072 '''
1073 with _toCartesian3(self, point2, point3, wrap) as cs:
1074 return _MODS.vector2d._radii11ABC4(*cs, useZ=True)[0]
1076 def _rhumb3(self, exact, radius): # != .sphericalBase._rhumbs3
1077 '''(INTERNAL) Get the C{rhumb} for this point's datum or for
1078 the B{C{radius}}' earth model iff non-C{None}.
1079 '''
1080 try:
1081 d = self._rhumb3dict
1082 t = d[(exact, radius)]
1083 except KeyError:
1084 D = self.datum if radius is None else \
1085 _spherical_datum(radius) # ellipsoidal OK
1086 try:
1087 r = D.ellipsoid.rhumb_(exact=exact) # or D.isSpherical
1088 except AttributeError as x:
1089 raise _AttributeError(datum=D, radius=radius, cause=x)
1090 t = r, D, _MODS.karney.Caps
1091 if len(d) > 2:
1092 d.clear() # d[:] = {}
1093 d[(exact, radius)] = t # cache 3-tuple
1094 return t
1096 @Property_RO
1097 def _rhumb3dict(self): # in ._update
1098 return {} # 3-item cache
1100 def rhumbAzimuthTo(self, other, exact=False, radius=None, wrap=False, b360=False):
1101 '''Return the azimuth (bearing) of a rhumb line (loxodrome) between this and
1102 an other (ellipsoidal) point.
1104 @arg other: The other point (C{LatLon}).
1105 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method
1106 L{Ellipsoid.rhumb_}.
1107 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},
1108 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's datum.
1109 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the B{C{other}} point (C{bool}).
1110 @kwarg b360: If C{True}, return the azimuth as bearing in compass degrees (C{bool}).
1112 @return: Rhumb azimuth (C{degrees180} or compass C{degrees360}).
1114 @raise TypeError: The B{C{other}} point is incompatible or B{C{radius}} is invalid.
1115 '''
1116 r, _, Cs = self._rhumb3(exact, radius)
1117 z = r._Inverse(self, other, wrap, outmask=Cs.AZIMUTH).azi12
1118 return _umod_360(z + _360_0) if b360 else z
1120 def rhumbDestination(self, distance, azimuth, radius=None, height=None, exact=False, **name):
1121 '''Return the destination point having travelled the given distance from this point along
1122 a rhumb line (loxodrome) of the given azimuth.
1124 @arg distance: Distance travelled (C{meter}, same units as this point's datum (ellipsoid)
1125 axes or B{C{radius}}, may be negative.
1126 @arg azimuth: Azimuth (bearing) of the rhumb line (compass C{degrees}).
1127 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},
1128 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's datum.
1129 @kwarg height: Optional height, overriding the default height (C{meter}).
1130 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method L{Ellipsoid.rhumb_}.
1131 @kwarg name: Optional C{B{name}=NN} (C{str}).
1133 @return: The destination point (ellipsoidal C{LatLon}).
1135 @raise TypeError: Invalid B{C{radius}}.
1137 @raise ValueError: Invalid B{C{distance}}, B{C{azimuth}}, B{C{radius}} or B{C{height}}.
1138 '''
1139 r, D, _ = self._rhumb3(exact, radius)
1140 d = r._Direct(self, azimuth, distance)
1141 h = self._heigHt(height)
1142 return self.classof(d.lat2, d.lon2, datum=D, height=h, **name)
1144 def rhumbDistanceTo(self, other, exact=False, radius=None, wrap=False):
1145 '''Return the distance from this to an other point along a rhumb line (loxodrome).
1147 @arg other: The other point (C{LatLon}).
1148 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method L{Ellipsoid.rhumb_}.
1149 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},
1150 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's datum.
1151 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the B{C{other}} point (C{bool}).
1153 @return: Distance (C{meter}, the same units as this point's datum (ellipsoid) axes or B{C{radius}}.
1155 @raise TypeError: The B{C{other}} point is incompatible or B{C{radius}} is invalid.
1157 @raise ValueError: Invalid B{C{radius}}.
1158 '''
1159 r, _, Cs = self._rhumb3(exact, radius)
1160 return r._Inverse(self, other, wrap, outmask=Cs.DISTANCE).s12
1162 def rhumbIntersecant2(self, circle, point, other, height=None,
1163 **exact_radius_wrap_eps_tol):
1164 '''Compute the intersections of a circle and a rhumb line given as two points or as a
1165 point and azimuth.
1167 @arg circle: Radius of the circle centered at this location (C{meter}), or a point
1168 on the circle (same C{LatLon} class).
1169 @arg point: The start point of the rhumb line (same C{LatLon} class).
1170 @arg other: An other point I{on} (same C{LatLon} class) or the azimuth I{of} (compass
1171 C{degrees}) the rhumb line.
1172 @kwarg height: Optional height for the intersection points (C{meter}, conventionally)
1173 or C{None} for interpolated heights.
1174 @kwarg exact_radius_wrap_eps_tol: Optional keyword arguments, see methods L{rhumbLine}
1175 and L{RhumbLineAux.Intersecant2} or L{RhumbLine.Intersecant2}.
1177 @return: 2-Tuple of the intersection points (representing a chord), each an instance of
1178 this class. Both points are the same instance if the rhumb line is tangent to
1179 the circle.
1181 @raise IntersectionError: The circle and rhumb line do not intersect.
1183 @raise TypeError: Invalid B{C{point}}, B{C{circle}} or B{C{other}}.
1185 @raise ValueError: Invalid B{C{circle}}, B{C{other}}, B{C{height}} or B{C{exact_radius_wrap}}.
1187 @see: Methods L{RhumbLineAux.Intersecant2} and L{RhumbLine.Intersecant2}.
1188 '''
1189 def _kwds3(eps=EPS, tol=_TOL, wrap=False, **kwds):
1190 return kwds, wrap, dict(eps=eps, tol=tol)
1192 exact_radius, w, eps_tol = _kwds3(**exact_radius_wrap_eps_tol)
1194 p = _unrollon(self, self.others(point=point), wrap=w)
1195 try:
1196 r = Radius_(circle=circle) if _isRadius(circle) else \
1197 self.rhumbDistanceTo(self.others(circle=circle), wrap=w, **exact_radius)
1198 rl = p.rhumbLine(other, wrap=w, **exact_radius)
1199 P, Q = rl.Intersecant2(self.lat, self.lon, r, **eps_tol)
1201 return self._intersecend2(p, other, w, height, rl.rhumb, P, Q,
1202 self.rhumbIntersecant2)
1203 except (TypeError, ValueError) as x:
1204 raise _xError(x, center=self, circle=circle, point=point, other=other,
1205 **exact_radius_wrap_eps_tol)
1207 def rhumbLine(self, other, exact=False, radius=None, wrap=False, **name_caps):
1208 '''Get a rhumb line through this point at a given azimuth or through this and an other point.
1210 @arg other: The azimuth I{of} (compass C{degrees}) or an other point I{on} (same
1211 C{LatLon} class) the rhumb line.
1212 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method L{Ellipsoid.rhumb_}.
1213 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},
1214 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's C{datum}.
1215 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the B{C{other}} point (C{bool}).
1216 @kwarg name_caps: Optional C{B{name}=str} and C{caps}, see L{RhumbLine} or L{RhumbLineAux} C{B{caps}}.
1218 @return: A C{RhumbLine} instance (C{RhumbLine} or C{RhumbLineAux}).
1220 @raise TypeError: Invalid B{C{radius}} or B{C{other}} not C{scalar} nor same C{LatLon} class.
1222 @see: Modules L{rhumb.aux_} and L{rhumb.ekx}.
1223 '''
1224 r, _, Cs = self._rhumb3(exact, radius)
1225 kwds = _xkwds(name_caps, name=self.name, caps=Cs.LINE_OFF)
1226 rl = r._DirectLine( self, other, **kwds) if _isDegrees(other) else \
1227 r._InverseLine(self, self.others(other), wrap, **kwds)
1228 return rl
1230 def rhumbMidpointTo(self, other, exact=False, radius=None, height=None, fraction=_0_5, **wrap_name):
1231 '''Return the (loxodromic) midpoint on the rhumb line between this and an other point.
1233 @arg other: The other point (same C{LatLon} class).
1234 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method L{Ellipsoid.rhumb_}.
1235 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},
1236 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's datum.
1237 @kwarg height: Optional height, overriding the mean height (C{meter}).
1238 @kwarg fraction: Midpoint location from this point (C{scalar}), 0 for this, 1 for the B{C{other}},
1239 0.5 for halfway between this and the B{C{other}} point, may be negative or
1240 greater than 1.
1241 @kwarg wrap_name: Optional C{B{name}=NN} (C{str}) and C{B{wrap}=False}, if C{True}, wrap or
1242 I{normalize} and unroll the B{C{other}} point (C{bool}).
1244 @return: The midpoint at the given B{C{fraction}} along the rhumb line (same C{LatLon} class).
1246 @raise TypeError: The B{C{other}} point is incompatible or B{C{radius}} is invalid.
1248 @raise ValueError: Invalid B{C{height}} or B{C{fraction}}.
1249 '''
1250 w, n = self._wrap_name2(**wrap_name)
1251 r, D, _ = self._rhumb3(exact, radius)
1252 f = Scalar(fraction=fraction)
1253 d = r._Inverse(self, self.others(other), w) # C.AZIMUTH_DISTANCE
1254 d = r._Direct( self, d.azi12, d.s12 * f)
1255 h = self._havg(other, f=f, h=height)
1256 return self.classof(d.lat2, d.lon2, datum=D, height=h, name=n)
1258 @property_RO
1259 def sphericalLatLon(self):
1260 '''Get the C{LatLon type} iff spherical, overloaded in L{LatLonSphericalBase}.
1261 '''
1262 return False
1264 def thomasTo(self, other, **wrap):
1265 '''Compute the distance between this and an other point using U{Thomas'
1266 <https://apps.DTIC.mil/dtic/tr/fulltext/u2/703541.pdf>} formula.
1268 @arg other: The other point (C{LatLon}).
1269 @kwarg wrap: Optional keyword argument C{B{wrap}=False}, if C{True}, wrap
1270 or I{normalize} and unroll the B{C{other}} point (C{bool}).
1272 @return: Distance (C{meter}, same units as the axes of this point's datum ellipsoid).
1274 @raise TypeError: The B{C{other}} point is not C{LatLon}.
1276 @see: Function L{pygeodesy.thomas} and methods L{cosineLawTo}, C{distanceTo*},
1277 L{equirectangularTo}, L{euclideanTo}, L{flatLocalTo} / L{hubenyTo},
1278 L{flatPolarTo}, L{haversineTo} and L{vincentysTo}.
1279 '''
1280 return self._distanceTo_(_formy.thomas_, other, **wrap)
1282 @deprecated_method
1283 def to2ab(self): # PYCHOK no cover
1284 '''DEPRECATED, use property L{philam}.'''
1285 return self.philam
1287 def toCartesian(self, height=None, Cartesian=None, **Cartesian_kwds):
1288 '''Convert this point to cartesian, I{geocentric} coordinates, also known as
1289 I{Earth-Centered, Earth-Fixed} (ECEF).
1291 @kwarg height: Optional height, overriding this point's height (C{meter},
1292 conventionally).
1293 @kwarg Cartesian: Optional class to return the geocentric coordinates
1294 (C{Cartesian}) or C{None}.
1295 @kwarg Cartesian_kwds: Optionally, additional B{C{Cartesian}} keyword
1296 arguments, ignored if C{B{Cartesian} is None}.
1298 @return: A B{C{Cartesian}} instance or if B{C{Cartesian} is None}, an
1299 L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
1300 C{C=0} and C{M} if available.
1302 @raise TypeError: Invalid B{C{Cartesian}} or B{C{Cartesian_kwds}} item.
1304 @see: Methods C{toNvector}, C{toVector} and C{toVector3d}.
1305 '''
1306 r = self._ecef9 if height is None else self.toEcef(height=height)
1307 if Cartesian is not None: # class or .classof
1308 r = Cartesian(r, **self._name1__(Cartesian_kwds))
1309 _xdatum(r.datum, self.datum)
1310 return r
1312 def _toCartesianEcef(self, height=None, i=None, up=2, **name_point):
1313 '''(INTERNAL) Convert to cartesian and check Ecef's before and after.
1314 '''
1315 p = self.others(up=up, **name_point)
1316 c = p.toCartesian(height=height)
1317 E = self.Ecef
1318 if E:
1319 for p in (p, c):
1320 e = _xattr(p, Ecef=None)
1321 if not _isin(e, None, E): # PYCHOK no cover
1322 n, _ = _xkwds_item2(name_point)
1323 n = Fmt.INDEX(n, i)
1324 t = _incompatible(typename(E))
1325 raise _ValueError(n, e, txt=t) # txt__
1326 return c
1328 def toDatum(self, datum2, height=None, **name):
1329 '''I{Must be overloaded}.'''
1330 self._notOverloaded(datum2, height=height, **name)
1332 def toEcef(self, height=None, M=False):
1333 '''Convert this point to I{geocentric} coordinates, also known as
1334 I{Earth-Centered, Earth-Fixed} (U{ECEF<https://WikiPedia.org/wiki/ECEF>}).
1336 @kwarg height: Optional height, overriding this point's height (C{meter},
1337 conventionally).
1338 @kwarg M: Optionally, include the rotation L{EcefMatrix} (C{bool}).
1340 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
1341 C{C=0} and C{M} if available.
1343 @raise EcefError: A C{.datum} or an ECEF issue.
1344 '''
1345 return self._ecef9 if _isin(height, None, self.height) else \
1346 self._Ecef_forward(self.lat, self.lon, height=height, M=M)
1348 @deprecated_method
1349 def to3llh(self, height=None): # PYCHOK no cover
1350 '''DEPRECATED, use property L{latlonheight} or C{latlon.to3Tuple(B{height})}.'''
1351 return self.latlonheight if _isin(height, None, self.height) else \
1352 self.latlon.to3Tuple(height)
1354 def toNormal(self, deep=False, **name):
1355 '''Get this point I{normalized} to C{abs(lat) <= 90} and C{abs(lon) <= 180}.
1357 @kwarg deep: If C{True}, make a deep, otherwise a shallow copy (C{bool}).
1358 @kwarg name: Optional C{B{name}=NN} (C{str}).
1360 @return: A copy of this point, I{normalized} (C{LatLon}), optionally renamed.
1362 @see: Property L{isnormal}, method L{normal} and function L{pygeodesy.normal}.
1363 '''
1364 ll = self.copy(deep=deep)
1365 _ = ll.normal()
1366 if name:
1367 ll.rename(name)
1368 return ll
1370 def toNvector(self, h=None, Nvector=None, **name_Nvector_kwds):
1371 '''Convert this point to C{n-vector} (normal to the earth's surface) components,
1372 I{including height}.
1374 @kwarg h: Optional height, overriding this point's height (C{meter}).
1375 @kwarg Nvector: Optional class to return the C{n-vector} components (C{Nvector})
1376 or C{None}.
1377 @kwarg name_Nvector_kwds: Optional C{B{name}=NN} (C{str}) and optionally,
1378 additional B{C{Nvector}} keyword arguments, ignored if C{B{Nvector}
1379 is None}.
1381 @return: An B{C{Nvector}} instance or a L{Vector4Tuple}C{(x, y, z, h)} if
1382 C{B{Nvector} is None}.
1384 @raise TypeError: Invalid B{C{h}}, B{C{Nvector}} or B{C{name_Nvector_kwds}}.
1386 @see: Methods C{toCartesian}, C{toVector} and C{toVector3d}.
1387 '''
1388 h = self._heigHt(h)
1389 if Nvector is None:
1390 r = self._n_xyz3.to4Tuple(h)
1391 n, _ = _name2__(name_Nvector_kwds, _or_nameof=self)
1392 if n:
1393 r.rename(n)
1394 else:
1395 x, y, z = self._n_xyz3
1396 r = Nvector(x, y, z, h=h, ll=self, **self._name1__(name_Nvector_kwds))
1397 return r
1399 def toStr(self, form=F_DMS, joined=_COMMASPACE_, m=_m_, **prec_sep_s_D_M_S): # PYCHOK expected
1400 '''Convert this point to a "lat, lon[, +/-height]" string, formatted in the
1401 given C{B{form}at}.
1403 @kwarg form: The lat-/longitude C{B{form}at} to use (C{str}), see functions
1404 L{pygeodesy.latDMS} or L{pygeodesy.lonDMS}.
1405 @kwarg joined: Separator to join the lat-, longitude and height strings (C{str}
1406 or C{None} or C{NN} for non-joined).
1407 @kwarg m: Optional unit of the height (C{str}), use C{None} to exclude height
1408 from the returned string.
1409 @kwarg prec_sep_s_D_M_S: Optional C{B{prec}ision}, C{B{sep}arator}, B{C{s_D}},
1410 B{C{s_M}}, B{C{s_S}} and B{C{s_DMS}} keyword arguments, see function
1411 L{pygeodesy.toDMS} for details.
1413 @return: This point in the specified C{B{form}at}, etc. (C{str} or a 2- or 3-tuple
1414 C{(lat_str, lon_str[, height_str])} if B{C{joined}} is C{NN} or C{None}).
1416 @see: Function L{pygeodesy.latDMS} or L{pygeodesy.lonDMS} for more details about
1417 keyword arguments C{B{form}at}, C{B{prec}ision}, C{B{sep}arator}, B{C{s_D}},
1418 B{C{s_M}}, B{C{s_S}} and B{C{s_DMS}}.
1419 '''
1420 t = (latDMS(self.lat, form=form, **prec_sep_s_D_M_S),
1421 lonDMS(self.lon, form=form, **prec_sep_s_D_M_S))
1422 if self.height and m is not None:
1423 t += (self.heightStr(m=m),)
1424 return joined.join(t) if joined else t
1426 def toVector(self, Vector=None, **Vector_kwds):
1427 '''Convert this point to a C{Vector} with the I{geocentric} C{(x, y, z)} (ECEF)
1428 coordinates, I{ignoring height}.
1430 @kwarg Vector: Optional class to return the I{geocentric} components (L{Vector3d})
1431 or C{None}.
1432 @kwarg Vector_kwds: Optionally, additional B{C{Vector}} keyword arguments,
1433 ignored if C{B{Vector} is None}.
1435 @return: A B{C{Vector}} instance or a L{Vector3Tuple}C{(x, y, z)} if C{B{Vector}
1436 is None}.
1438 @raise TypeError: Invalid B{C{Vector}} or B{C{Vector_kwds}}.
1440 @see: Methods C{toCartesian}, C{toNvector} and C{toVector3d}.
1441 '''
1442 return self._ecef9.toVector(Vector=Vector, **self._name1__(Vector_kwds))
1444 def toVector3d(self, norm=True, **Vector3d_kwds):
1445 '''Convert this point to a L{Vector3d} with the I{geocentric} C{(x, y, z)}
1446 (ECEF) coordinates, I{ignoring height}.
1448 @kwarg norm: If C{False}, don't normalize the coordinates (C{bool}).
1449 @kwarg Vector3d_kwds: Optional L{Vector3d} keyword arguments.
1451 @return: Named, unit vector or vector (L{Vector3d}).
1453 @raise TypeError: Invalid B{C{Vector3d_kwds}}.
1455 @see: Methods C{toCartesian}, C{toNvector} and C{toVector}.
1456 '''
1457 r = self.toVector(Vector=_MODS.vector3d.Vector3d, **Vector3d_kwds)
1458 if norm:
1459 r = r.unit(ll=self)
1460 return r
1462 def toWm(self, **toWm_kwds):
1463 '''Convert this point to a WM coordinate.
1465 @kwarg toWm_kwds: Optional L{pygeodesy.toWm} keyword arguments.
1467 @return: The WM coordinate (L{Wm}).
1469 @see: Function L{pygeodesy.toWm}.
1470 '''
1471 return _MODS.webmercator.toWm(self, **self._name1__(toWm_kwds))
1473 @deprecated_method
1474 def to3xyz(self): # PYCHOK no cover
1475 '''DEPRECATED, use property L{xyz} or method L{toNvector}, L{toVector},
1476 L{toVector3d} or perhaps (geocentric) L{toEcef}.'''
1477 return self.xyz # self.toVector()
1479# def _update(self, updated, *attrs, **setters):
1480# '''(INTERNAL) See C{_NamedBase._update}.
1481# '''
1482# if updated:
1483# self._rhumb3dict.clear()
1484# return _NamedBase._update(self, updated, *attrs, **setters)
1486 def vincentysTo(self, other, **radius_wrap):
1487 '''Compute the distance between this and an other point using U{Vincenty's
1488 <https://WikiPedia.org/wiki/Great-circle_distance>} spherical formula.
1490 @arg other: The other point (C{LatLon}).
1491 @kwarg radius_wrap: Optional C{B{radius}=R_M} and C{B{wrap}=False} for
1492 function L{pygeodesy.vincentys}, overriding the default
1493 C{mean radius} of this point's datum ellipsoid.
1495 @return: Distance (C{meter}, same units as B{C{radius}}).
1497 @raise TypeError: The B{C{other}} point is not C{LatLon}.
1499 @see: Function L{pygeodesy.vincentys} and methods L{cosineLawTo}, C{distanceTo*},
1500 L{equirectangularTo}, L{euclideanTo}, L{flatLocalTo} / L{hubenyTo},
1501 L{flatPolarTo}, L{haversineTo} and L{thomasTo}.
1502 '''
1503 return self._distanceTo(_formy.vincentys, other, **_xkwds(radius_wrap, radius=None))
1505 def _wrap_name2(self, wrap=False, **name):
1506 '''(INTERNAL) Return the C{wrap} and C{name} value.
1507 '''
1508 return wrap, (self._name__(name) if name else NN)
1510 @property_RO
1511 def xyz(self):
1512 '''Get the I{geocentric} C{(x, y, z)} coordinates (L{Vector3Tuple}C{(x, y, z)})
1513 '''
1514 return self._ecef9.xyz
1516 @property_RO
1517 def xyz3(self):
1518 '''Get the I{geocentric} C{(x, y, z)} coordinates as C{3-tuple}.
1519 '''
1520 return tuple(self.xyz)
1522 @Property_RO
1523 def xyzh(self):
1524 '''Get the I{geocentric} C{(x, y, z)} coordinates and height (L{Vector4Tuple}C{(x, y, z, h)})
1525 '''
1526 return self.xyz.to4Tuple(self.height)
1529class _toCartesian3(object): # see also .formy._idllmn6, .geodesicw._wargs, .vector2d._numpy
1530 '''(INTERNAL) Wrapper to convert 2 other points.
1531 '''
1532 @contextmanager # <https://www.Python.org/dev/peps/pep-0343/> Examples
1533 def __call__(self, p, p2, p3, wrap, **kwds):
1534 try:
1535 if wrap:
1536 p2, p3 = map1(_Wrap.point, p2, p3)
1537 kwds = _xkwds(kwds, wrap=wrap)
1538 yield (p. toCartesian().copy(name=_point_), # copy to rename
1539 p._toCartesianEcef(up=4, point2=p2),
1540 p._toCartesianEcef(up=4, point3=p3))
1541 except (AssertionError, TypeError, ValueError) as x: # Exception?
1542 raise _xError(x, point=p, point2=p2, point3=p3, **kwds)
1544_toCartesian3 = _toCartesian3() # PYCHOK singleton
1547def _latlonheight3(latlonh, height, wrap): # in .points.LatLon_.__init__
1548 '''(INTERNAL) Get 3-tuple C{(lat, lon, height)}.
1549 '''
1550 try:
1551 lat, lon = latlonh.lat, latlonh.lon
1552 height = _xattr(latlonh, height=height)
1553 except AttributeError:
1554 raise _IsnotError(_LatLon_, latlonh=latlonh)
1555 if wrap:
1556 lat, lon = _Wrap.latlon(lat, lon)
1557 return lat, lon, height
1560def latlon2n_xyz(lat_ll, lon=None, **name):
1561 '''Convert lat-, longitude to C{n-vector} (I{normal} to the earth's surface) X, Y and Z components.
1563 @arg lat_ll: Latitude (C{degrees}) or a C{LatLon} instance, L{LatLon2Tuple} or other C{LatLon*Tuple}.
1564 @kwarg lon: Longitude (C{degrees}), required if C{B{lon_ll} is degrees}, ignored otherwise.
1565 @kwarg name: Optional C{B{name}=NN} (C{str}).
1567 @return: A L{Vector3Tuple}C{(x, y, z)}.
1569 @see: Function L{philam2n_xyz}.
1571 @note: These are C{n-vector} x, y and z components, I{NOT geocentric} x, y and z (ECEF) coordinates!
1572 '''
1573 lat = lat_ll
1574 if lon is None:
1575 try:
1576 lat, lon = lat_ll.latlon
1577 except AttributeError:
1578 lat = lat_ll.lat
1579 lon = lat_ll.lon
1580 # Kenneth Gade eqn 3, but using right-handed
1581 # vector x -> 0°E,0°N, y -> 90°E,0°N, z -> 90°N
1582 sa, ca, sb, cb = sincos2d_(lat, lon)
1583 return Vector3Tuple(ca * cb, ca * sb, sa, **name)
1586def philam2n_xyz(phi_ll, lam=None, **name):
1587 '''Convert lat-, longitude to C{n-vector} (I{normal} to the earth's surface) X, Y and Z components.
1589 @arg phi_ll: Latitude (C{radians}) or a C{LatLon} instance with C{phi}, C{lam} or C{philam} attributes.
1590 @kwarg lam: Longitude (C{radians}), required if C{B{phi_ll} is radians}, ignored otherwise.
1591 @kwarg name: Optional name (C{str}).
1593 @return: A L{Vector3Tuple}C{(x, y, z)}.
1595 @see: Function L{latlon2n_xyz}.
1597 @note: These are C{n-vector} x, y and z components, I{NOT geocentric} x, y and z (ECEF) coordinates!
1598 '''
1599 phi = phi_ll
1600 if lam is None:
1601 try:
1602 phi, lam = phi_ll.philam
1603 except AttributeError:
1604 phi = phi_ll.phi
1605 lam = phi_ll.lam
1606 return latlon2n_xyz(degrees(phi), degrees(lam), **name)
1609def _trilaterate5(p1, d1, p2, d2, p3, d3, area=True, eps=EPS1, radius=R_M, wrap=False): # MCCABE 13
1610 '''(INTERNAL) Trilaterate three points by I{area overlap} or by I{perimeter intersection} of three circles.
1612 @note: The B{C{radius}} is needed only for C{n-vectorial} and C{sphericalTrigonometry.LatLon.distanceTo}
1613 methods and silently ignored by the C{ellipsoidalExact}, C{-GeodSolve}, C{-Karney} and
1614 C{-Vincenty.LatLon.distanceTo} methods.
1615 '''
1616 p2, p3, w = _unrollon3(p1, p2, p3, wrap)
1617 rw = dict(radius=radius, wrap=w)
1619 r1 = Distance_(distance1=d1)
1620 r2 = Distance_(distance2=d2)
1621 r3 = Distance_(distance3=d3)
1622 m = 0 if area else (r1 + r2 + r3)
1623 pc = 0
1624 t = []
1625 for _ in range(3):
1626 try: # intersection of circle (p1, r1) and (p2, r2)
1627 c1, c2 = p1.intersections2(r1, p2, r2, wrap=w)
1629 if area: # check overlap
1630 if c1 is c2: # abutting
1631 c = c1
1632 else: # nearest point on radical
1633 c = p3.nearestOn(c1, c2, within=True, wrap=w)
1634 d = r3 - p3.distanceTo(c, **rw)
1635 if d > eps: # sufficient overlap
1636 t.append((d, c))
1637 m = max(m, d)
1639 else: # check intersection
1640 for c in ((c1,) if c1 is c2 else (c1, c2)):
1641 d = fabs(r3 - p3.distanceTo(c, **rw))
1642 if d < eps: # below margin
1643 t.append((d, c))
1644 m = min(m, d)
1646 except IntersectionError as x:
1647 if _concentric_ in str(x): # XXX ConcentricError?
1648 pc += 1
1650 p1, r1, p2, r2, p3, r3 = p2, r2, p3, r3, p1, r1 # rotate
1652 if t: # get min, max, points and count ...
1653 t = tuple(sorted(t))
1654 n = len(t), # as 1-tuple
1655 # ... or for a single trilaterated result,
1656 # min *is* max, min- *is* maxPoint and n=1, 2 or 3
1657 return Trilaterate5Tuple(t[0] + t[-1] + n) # *(t[0] + ...)
1659 elif area and pc == 3: # all pairwise concentric ...
1660 r, p = min((r1, p1), (r2, p2), (r3, p3))
1661 m = max(r1, r2, r3)
1662 # ... return "smallest" point twice, the smallest
1663 # and largest distance and n=0 for concentric
1664 return Trilaterate5Tuple(float(r), p, float(m), p, 0)
1666 n, f = (_overlap_, max) if area else (_intersection_, min)
1667 t = _COMMASPACE_(_no_(n), '%s %.3g' % (typename(f), m))
1668 raise IntersectionError(area=area, eps=eps, wrap=wrap, txt=t)
1671__all__ += _ALL_DOCS(LatLonBase)
1673# **) MIT License
1674#
1675# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved.
1676#
1677# Permission is hereby granted, free of charge, to any person obtaining a
1678# copy of this software and associated documentation files (the "Software"),
1679# to deal in the Software without restriction, including without limitation
1680# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1681# and/or sell copies of the Software, and to permit persons to whom the
1682# Software is furnished to do so, subject to the following conditions:
1683#
1684# The above copyright notice and this permission notice shall be included
1685# in all copies or substantial portions of the Software.
1686#
1687# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1688# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1689# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1690# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1691# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1692# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1693# OTHER DEALINGS IN THE SOFTWARE.