Coverage for pygeodesy/latlonBase.py: 93%
474 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-04-25 13:15 -0400
« prev ^ index » next coverage.py v7.6.1, created at 2025-04-25 13:15 -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.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 import formy as _formy # .MODS.into
26from pygeodesy.internals import _passarg, typename
27from pygeodesy.interns import NN, _COMMASPACE_, _concentric_, _height_, \
28 _intersection_, _LatLon_, _m_, _negative_, \
29 _no_, _overlap_, _too_, _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, _NamedLocal, 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.04.21'
53_formy = _MODS.into(formy=__name__)
56class LatLonBase(_NamedBase, _NamedLocal):
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)
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 def nearestOn6(self, points, closed=False, height=None, wrap=False):
905 '''Locate the point on a path or polygon closest to this point.
907 Points are converted to and distances are computed in I{geocentric},
908 cartesian space.
910 @arg points: The path or polygon points (C{LatLon}[]).
911 @kwarg closed: Optionally, close the polygon (C{bool}).
912 @kwarg height: Optional height, overriding the height of this and all
913 other points (C{meter}). If C{None}, take the height
914 of points into account for distances.
915 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the B{C{points}}
916 (C{bool}).
918 @return: A L{NearestOn6Tuple}C{(closest, distance, fi, j, start, end)}
919 with the C{closest}, the C{start} and the C{end} point each an
920 instance of this C{LatLon} and C{distance} in C{meter}, same
921 units as the cartesian axes.
923 @raise PointsError: Insufficient number of B{C{points}}.
925 @raise TypeError: Some B{C{points}} or some B{C{points}}' C{Ecef} invalid.
927 @raise ValueError: Some B{C{points}}' C{Ecef} is incompatible.
929 @see: Function L{nearestOn6<pygeodesy.nearestOn6>}.
930 '''
931 def _cs(Ps, h, w, C):
932 p = None # not used
933 for i, q in Ps.enumerate():
934 if w and i:
935 q = _unrollon(p, q)
936 yield C(height=h, i=i, up=3, points=q)
937 p = q
939 C = self._toCartesianEcef # to verify datum and Ecef
940 Ps = self.PointsIter(points, wrap=wrap)
942 c = C(height=height, this=self) # this Cartesian
943 t = _MODS.vector3d.nearestOn6(c, _cs(Ps, height, wrap, C), closed=closed)
944 c, s, e = t.closest, t.start, t.end
946 kwds = _xkwds_not(None, LatLon=self.classof, # this LatLon
947 height=height)
948 _r = self.Ecef(self.datum).reverse
949 p = _r(c).toLatLon(**kwds)
950 s = _r(s).toLatLon(**kwds) if s is not c else p
951 e = _r(e).toLatLon(**kwds) if e is not c else p
952 return t.dup(closest=p, start=s, end=e)
954 def nearestTo(self, *args, **kwds): # PYCHOK no cover
955 '''B{Not implemented}, throws a C{NotImplementedError} always.'''
956 self._notImplemented(*args, **kwds)
958 def normal(self):
959 '''Normalize this point I{in-place} to C{abs(lat) <= 90} and C{abs(lon) <= 180}.
961 @return: C{True} if this point was I{normal}, C{False} if it wasn't (but is now).
963 @see: Property L{isnormal} and method L{toNormal}.
964 '''
965 n = self.isnormal
966 if not n:
967 self.latlon = _formy.normal(*self.latlon)
968 return n
970 @property_RO
971 def _N_vector(self):
972 '''(INTERNAL) Get the C{Nvector} (C{nvectorBase._N_vector_})
973 '''
974 _N = _MODS.nvectorBase._N_vector_
975 return _N(*self._n_xyz3, h=self.height, name=self.name)
977 @Property_RO
978 def _n_xyz3(self):
979 '''(INTERNAL) Get the n-vector components as L{Vector3Tuple}.
980 '''
981 return philam2n_xyz(self.phi, self.lam, name=self.name)
983 @Property_RO
984 def phi(self):
985 '''Get the latitude (B{C{radians}}).
986 '''
987 return radians(self.lat)
989 @Property_RO
990 def philam(self):
991 '''Get the lat- and longitude (L{PhiLam2Tuple}C{(phi, lam)}).
992 '''
993 return PhiLam2Tuple(self.phi, self.lam, name=self.name)
995 def philam2(self, ndigits=0):
996 '''Return this point's lat- and longitude in C{radians}, rounded.
998 @kwarg ndigits: Number of (decimal) digits (C{int}).
1000 @return: A L{PhiLam2Tuple}C{(phi, lam)}, both C{float} and rounded
1001 away from zero.
1003 @note: The C{round}ed values are C{float}, always.
1004 '''
1005 return PhiLam2Tuple(round(self.phi, ndigits),
1006 round(self.lam, ndigits), name=self.name)
1008 @Property_RO
1009 def philamheight(self):
1010 '''Get the lat-, longitude in C{radians} and height (L{PhiLam3Tuple}C{(phi, lam, height)}).
1011 '''
1012 return self.philam.to3Tuple(self.height)
1014 @deprecated_method
1015 def points(self, points, **closed): # PYCHOK no cover
1016 '''DEPRECATED, use method L{points2}.'''
1017 return self.points2(points, **closed)
1019 def points2(self, points, closed=True):
1020 '''Check a path or polygon represented by points.
1022 @arg points: The path or polygon points (C{LatLon}[])
1023 @kwarg closed: Optionally, consider the polygon closed, ignoring any
1024 duplicate or closing final B{C{points}} (C{bool}).
1026 @return: A L{Points2Tuple}C{(number, points)}, an C{int} and a C{list}
1027 or C{tuple}.
1029 @raise PointsError: Insufficient number of B{C{points}}.
1031 @raise TypeError: Some B{C{points}} are not C{LatLon}.
1032 '''
1033 return _MODS.iters.points2(points, closed=closed, base=self)
1035 def PointsIter(self, points, loop=0, dedup=False, wrap=False):
1036 '''Return a C{PointsIter} iterator.
1038 @arg points: The path or polygon points (C{LatLon}[])
1039 @kwarg loop: Number of loop-back points (non-negative C{int}).
1040 @kwarg dedup: If C{True}, skip duplicate points (C{bool}).
1041 @kwarg wrap: If C{True}, wrap or I{normalize} the enum-/iterated
1042 B{C{points}} (C{bool}).
1044 @return: A new C{PointsIter} iterator.
1046 @raise PointsError: Insufficient number of B{C{points}}.
1047 '''
1048 return _MODS.iters.PointsIter(points, base=self, loop=loop,
1049 dedup=dedup, wrap=wrap)
1051 def radii11(self, point2, point3, wrap=False):
1052 '''Return the radii of the C{Circum-}, C{In-}, I{Soddy} and C{Tangent}
1053 circles of a (planar) triangle formed by this and two other points.
1055 @arg point2: Second point (C{LatLon}).
1056 @arg point3: Third point (C{LatLon}).
1057 @kwarg wrap: If C{True}, wrap or I{normalize} B{C{point2}} and
1058 B{C{point3}} (C{bool}).
1060 @return: L{Radii11Tuple}C{(rA, rB, rC, cR, rIn, riS, roS, a, b, c, s)}.
1062 @raise IntersectionError: Near-coincident or -colinear points.
1064 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}.
1066 @see: Function L{pygeodesy.radii11}, U{Incircle
1067 <https://MathWorld.Wolfram.com/Incircle.html>}, U{Soddy Circles
1068 <https://MathWorld.Wolfram.com/SoddyCircles.html>} and U{Tangent
1069 Circles<https://MathWorld.Wolfram.com/TangentCircles.html>}.
1070 '''
1071 with _toCartesian3(self, point2, point3, wrap) as cs:
1072 return _MODS.vector2d._radii11ABC4(*cs, useZ=True)[0]
1074 def _rhumb3(self, exact, radius): # != .sphericalBase._rhumbs3
1075 '''(INTERNAL) Get the C{rhumb} for this point's datum or for
1076 the B{C{radius}}' earth model iff non-C{None}.
1077 '''
1078 try:
1079 d = self._rhumb3dict
1080 t = d[(exact, radius)]
1081 except KeyError:
1082 D = self.datum if radius is None else \
1083 _spherical_datum(radius) # ellipsoidal OK
1084 try:
1085 r = D.ellipsoid.rhumb_(exact=exact) # or D.isSpherical
1086 except AttributeError as x:
1087 raise _AttributeError(datum=D, radius=radius, cause=x)
1088 t = r, D, _MODS.karney.Caps
1089 if len(d) > 2:
1090 d.clear() # d[:] = {}
1091 d[(exact, radius)] = t # cache 3-tuple
1092 return t
1094 @Property_RO
1095 def _rhumb3dict(self): # in ._update
1096 return {} # 3-item cache
1098 def rhumbAzimuthTo(self, other, exact=False, radius=None, wrap=False, b360=False):
1099 '''Return the azimuth (bearing) of a rhumb line (loxodrome) between this and
1100 an other (ellipsoidal) point.
1102 @arg other: The other point (C{LatLon}).
1103 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method
1104 L{Ellipsoid.rhumb_}.
1105 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},
1106 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's datum.
1107 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the B{C{other}} point (C{bool}).
1108 @kwarg b360: If C{True}, return the azimuth as bearing in compass degrees (C{bool}).
1110 @return: Rhumb azimuth (C{degrees180} or compass C{degrees360}).
1112 @raise TypeError: The B{C{other}} point is incompatible or B{C{radius}} is invalid.
1113 '''
1114 r, _, Cs = self._rhumb3(exact, radius)
1115 z = r._Inverse(self, other, wrap, outmask=Cs.AZIMUTH).azi12
1116 return _umod_360(z + _360_0) if b360 else z
1118 def rhumbDestination(self, distance, azimuth, radius=None, height=None, exact=False, **name):
1119 '''Return the destination point having travelled the given distance from this point along
1120 a rhumb line (loxodrome) of the given azimuth.
1122 @arg distance: Distance travelled (C{meter}, same units as this point's datum (ellipsoid)
1123 axes or B{C{radius}}, may be negative.
1124 @arg azimuth: Azimuth (bearing) of the rhumb line (compass C{degrees}).
1125 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},
1126 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's datum.
1127 @kwarg height: Optional height, overriding the default height (C{meter}).
1128 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method L{Ellipsoid.rhumb_}.
1129 @kwarg name: Optional C{B{name}=NN} (C{str}).
1131 @return: The destination point (ellipsoidal C{LatLon}).
1133 @raise TypeError: Invalid B{C{radius}}.
1135 @raise ValueError: Invalid B{C{distance}}, B{C{azimuth}}, B{C{radius}} or B{C{height}}.
1136 '''
1137 r, D, _ = self._rhumb3(exact, radius)
1138 d = r._Direct(self, azimuth, distance)
1139 h = self._heigHt(height)
1140 return self.classof(d.lat2, d.lon2, datum=D, height=h, **name)
1142 def rhumbDistanceTo(self, other, exact=False, radius=None, wrap=False):
1143 '''Return the distance from this to an other point along a rhumb line (loxodrome).
1145 @arg other: The other point (C{LatLon}).
1146 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method L{Ellipsoid.rhumb_}.
1147 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},
1148 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's datum.
1149 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the B{C{other}} point (C{bool}).
1151 @return: Distance (C{meter}, the same units as this point's datum (ellipsoid) axes or B{C{radius}}.
1153 @raise TypeError: The B{C{other}} point is incompatible or B{C{radius}} is invalid.
1155 @raise ValueError: Invalid B{C{radius}}.
1156 '''
1157 r, _, Cs = self._rhumb3(exact, radius)
1158 return r._Inverse(self, other, wrap, outmask=Cs.DISTANCE).s12
1160 def rhumbIntersecant2(self, circle, point, other, height=None,
1161 **exact_radius_wrap_eps_tol):
1162 '''Compute the intersections of a circle and a rhumb line given as two points or as a
1163 point and azimuth.
1165 @arg circle: Radius of the circle centered at this location (C{meter}), or a point
1166 on the circle (same C{LatLon} class).
1167 @arg point: The start point of the rhumb line (same C{LatLon} class).
1168 @arg other: An other point I{on} (same C{LatLon} class) or the azimuth I{of} (compass
1169 C{degrees}) the rhumb line.
1170 @kwarg height: Optional height for the intersection points (C{meter}, conventionally)
1171 or C{None} for interpolated heights.
1172 @kwarg exact_radius_wrap_eps_tol: Optional keyword arguments, see methods L{rhumbLine}
1173 and L{RhumbLineAux.Intersecant2} or L{RhumbLine.Intersecant2}.
1175 @return: 2-Tuple of the intersection points (representing a chord), each an instance of
1176 this class. Both points are the same instance if the rhumb line is tangent to
1177 the circle.
1179 @raise IntersectionError: The circle and rhumb line do not intersect.
1181 @raise TypeError: Invalid B{C{point}}, B{C{circle}} or B{C{other}}.
1183 @raise ValueError: Invalid B{C{circle}}, B{C{other}}, B{C{height}} or B{C{exact_radius_wrap}}.
1185 @see: Methods L{RhumbLineAux.Intersecant2} and L{RhumbLine.Intersecant2}.
1186 '''
1187 def _kwds3(eps=EPS, tol=_TOL, wrap=False, **kwds):
1188 return kwds, wrap, dict(eps=eps, tol=tol)
1190 exact_radius, w, eps_tol = _kwds3(**exact_radius_wrap_eps_tol)
1192 p = _unrollon(self, self.others(point=point), wrap=w)
1193 try:
1194 r = Radius_(circle=circle) if _isRadius(circle) else \
1195 self.rhumbDistanceTo(self.others(circle=circle), wrap=w, **exact_radius)
1196 rl = p.rhumbLine(other, wrap=w, **exact_radius)
1197 P, Q = rl.Intersecant2(self.lat, self.lon, r, **eps_tol)
1199 return self._intersecend2(p, other, w, height, rl.rhumb, P, Q,
1200 self.rhumbIntersecant2)
1201 except (TypeError, ValueError) as x:
1202 raise _xError(x, center=self, circle=circle, point=point, other=other,
1203 **exact_radius_wrap_eps_tol)
1205 def rhumbLine(self, other, exact=False, radius=None, wrap=False, **name_caps):
1206 '''Get a rhumb line through this point at a given azimuth or through this and an other point.
1208 @arg other: The azimuth I{of} (compass C{degrees}) or an other point I{on} (same
1209 C{LatLon} class) the rhumb line.
1210 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method L{Ellipsoid.rhumb_}.
1211 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},
1212 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's C{datum}.
1213 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the B{C{other}} point (C{bool}).
1214 @kwarg name_caps: Optional C{B{name}=str} and C{caps}, see L{RhumbLine} or L{RhumbLineAux} C{B{caps}}.
1216 @return: A C{RhumbLine} instance (C{RhumbLine} or C{RhumbLineAux}).
1218 @raise TypeError: Invalid B{C{radius}} or B{C{other}} not C{scalar} nor same C{LatLon} class.
1220 @see: Modules L{rhumb.aux_} and L{rhumb.ekx}.
1221 '''
1222 r, _, Cs = self._rhumb3(exact, radius)
1223 kwds = _xkwds(name_caps, name=self.name, caps=Cs.LINE_OFF)
1224 rl = r._DirectLine( self, other, **kwds) if _isDegrees(other) else \
1225 r._InverseLine(self, self.others(other), wrap, **kwds)
1226 return rl
1228 def rhumbMidpointTo(self, other, exact=False, radius=None, height=None, fraction=_0_5, **wrap_name):
1229 '''Return the (loxodromic) midpoint on the rhumb line between this and an other point.
1231 @arg other: The other point (same C{LatLon} class).
1232 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method L{Ellipsoid.rhumb_}.
1233 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},
1234 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's datum.
1235 @kwarg height: Optional height, overriding the mean height (C{meter}).
1236 @kwarg fraction: Midpoint location from this point (C{scalar}), 0 for this, 1 for the B{C{other}},
1237 0.5 for halfway between this and the B{C{other}} point, may be negative or
1238 greater than 1.
1239 @kwarg wrap_name: Optional C{B{name}=NN} (C{str}) and C{B{wrap}=False}, if C{True}, wrap or
1240 I{normalize} and unroll the B{C{other}} point (C{bool}).
1242 @return: The midpoint at the given B{C{fraction}} along the rhumb line (same C{LatLon} class).
1244 @raise TypeError: The B{C{other}} point is incompatible or B{C{radius}} is invalid.
1246 @raise ValueError: Invalid B{C{height}} or B{C{fraction}}.
1247 '''
1248 w, n = self._wrap_name2(**wrap_name)
1249 r, D, _ = self._rhumb3(exact, radius)
1250 f = Scalar(fraction=fraction)
1251 d = r._Inverse(self, self.others(other), w) # C.AZIMUTH_DISTANCE
1252 d = r._Direct( self, d.azi12, d.s12 * f)
1253 h = self._havg(other, f=f, h=height)
1254 return self.classof(d.lat2, d.lon2, datum=D, height=h, name=n)
1256 @property_RO
1257 def sphericalLatLon(self):
1258 '''Get the C{LatLon type} iff spherical, overloaded in L{LatLonSphericalBase}.
1259 '''
1260 return False
1262 def thomasTo(self, other, **wrap):
1263 '''Compute the distance between this and an other point using U{Thomas'
1264 <https://apps.DTIC.mil/dtic/tr/fulltext/u2/703541.pdf>} formula.
1266 @arg other: The other point (C{LatLon}).
1267 @kwarg wrap: Optional keyword argument C{B{wrap}=False}, if C{True}, wrap
1268 or I{normalize} and unroll the B{C{other}} point (C{bool}).
1270 @return: Distance (C{meter}, same units as the axes of this point's datum ellipsoid).
1272 @raise TypeError: The B{C{other}} point is not C{LatLon}.
1274 @see: Function L{pygeodesy.thomas} and methods L{cosineLawTo}, C{distanceTo*},
1275 L{equirectangularTo}, L{euclideanTo}, L{flatLocalTo} / L{hubenyTo},
1276 L{flatPolarTo}, L{haversineTo} and L{vincentysTo}.
1277 '''
1278 return self._distanceTo_(_formy.thomas_, other, **wrap)
1280 @deprecated_method
1281 def to2ab(self): # PYCHOK no cover
1282 '''DEPRECATED, use property L{philam}.'''
1283 return self.philam
1285 def toCartesian(self, height=None, Cartesian=None, **Cartesian_kwds):
1286 '''Convert this point to cartesian, I{geocentric} coordinates, also known as
1287 I{Earth-Centered, Earth-Fixed} (ECEF).
1289 @kwarg height: Optional height, overriding this point's height (C{meter},
1290 conventionally).
1291 @kwarg Cartesian: Optional class to return the geocentric coordinates
1292 (C{Cartesian}) or C{None}.
1293 @kwarg Cartesian_kwds: Optionally, additional B{C{Cartesian}} keyword
1294 arguments, ignored if C{B{Cartesian} is None}.
1296 @return: A B{C{Cartesian}} instance or if B{C{Cartesian} is None}, an
1297 L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
1298 C{C=0} and C{M} if available.
1300 @raise TypeError: Invalid B{C{Cartesian}} or B{C{Cartesian_kwds}} item.
1302 @see: Methods C{toNvector}, C{toVector} and C{toVector3d}.
1303 '''
1304 r = self._ecef9 if height is None else self.toEcef(height=height)
1305 if Cartesian is not None: # class or .classof
1306 r = Cartesian(r, **self._name1__(Cartesian_kwds))
1307 _xdatum(r.datum, self.datum)
1308 return r
1310 def _toCartesianEcef(self, height=None, i=None, up=2, **name_point):
1311 '''(INTERNAL) Convert to cartesian and check Ecef's before and after.
1312 '''
1313 p = self.others(up=up, **name_point)
1314 c = p.toCartesian(height=height)
1315 E = self.Ecef
1316 if E:
1317 for p in (p, c):
1318 e = _xattr(p, Ecef=None)
1319 if not _isin(e, None, E): # PYCHOK no cover
1320 n, _ = _xkwds_item2(name_point)
1321 n = Fmt.INDEX(n, i)
1322 t = _incompatible(typename(E))
1323 raise _ValueError(n, e, txt=t) # txt__
1324 return c
1326 def toDatum(self, datum2, height=None, **name):
1327 '''I{Must be overloaded}.'''
1328 self._notOverloaded(datum2, height=height, **name)
1330 def toEcef(self, height=None, M=False):
1331 '''Convert this point to I{geocentric} coordinates, also known as
1332 I{Earth-Centered, Earth-Fixed} (U{ECEF<https://WikiPedia.org/wiki/ECEF>}).
1334 @kwarg height: Optional height, overriding this point's height (C{meter},
1335 conventionally).
1336 @kwarg M: Optionally, include the rotation L{EcefMatrix} (C{bool}).
1338 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
1339 C{C=0} and C{M} if available.
1341 @raise EcefError: A C{.datum} or an ECEF issue.
1342 '''
1343 return self._ecef9 if _isin(height, None, self.height) else \
1344 self._Ecef_forward(self.lat, self.lon, height=height, M=M)
1346 @deprecated_method
1347 def to3llh(self, height=None): # PYCHOK no cover
1348 '''DEPRECATED, use property L{latlonheight} or C{latlon.to3Tuple(B{height})}.'''
1349 return self.latlonheight if _isin(height, None, self.height) else \
1350 self.latlon.to3Tuple(height)
1352 def toNormal(self, deep=False, **name):
1353 '''Get this point I{normalized} to C{abs(lat) <= 90} and C{abs(lon) <= 180}.
1355 @kwarg deep: If C{True}, make a deep, otherwise a shallow copy (C{bool}).
1356 @kwarg name: Optional C{B{name}=NN} (C{str}).
1358 @return: A copy of this point, I{normalized} (C{LatLon}), optionally renamed.
1360 @see: Property L{isnormal}, method L{normal} and function L{pygeodesy.normal}.
1361 '''
1362 ll = self.copy(deep=deep)
1363 _ = ll.normal()
1364 if name:
1365 ll.rename(name)
1366 return ll
1368 def toNvector(self, h=None, Nvector=None, **name_Nvector_kwds):
1369 '''Convert this point to C{n-vector} (normal to the earth's surface) components,
1370 I{including height}.
1372 @kwarg h: Optional height, overriding this point's height (C{meter}).
1373 @kwarg Nvector: Optional class to return the C{n-vector} components (C{Nvector})
1374 or C{None}.
1375 @kwarg name_Nvector_kwds: Optional C{B{name}=NN} (C{str}) and optionally,
1376 additional B{C{Nvector}} keyword arguments, ignored if C{B{Nvector}
1377 is None}.
1379 @return: An B{C{Nvector}} instance or a L{Vector4Tuple}C{(x, y, z, h)} if
1380 C{B{Nvector} is None}.
1382 @raise TypeError: Invalid B{C{h}}, B{C{Nvector}} or B{C{name_Nvector_kwds}}.
1384 @see: Methods C{toCartesian}, C{toVector} and C{toVector3d}.
1385 '''
1386 h = self._heigHt(h)
1387 if Nvector is None:
1388 r = self._n_xyz3.to4Tuple(h)
1389 n, _ = _name2__(name_Nvector_kwds, _or_nameof=self)
1390 if n:
1391 r.rename(n)
1392 else:
1393 x, y, z = self._n_xyz3
1394 r = Nvector(x, y, z, h=h, ll=self, **self._name1__(name_Nvector_kwds))
1395 return r
1397 def toStr(self, form=F_DMS, joined=_COMMASPACE_, m=_m_, **prec_sep_s_D_M_S): # PYCHOK expected
1398 '''Convert this point to a "lat, lon[, +/-height]" string, formatted in the
1399 given C{B{form}at}.
1401 @kwarg form: The lat-/longitude C{B{form}at} to use (C{str}), see functions
1402 L{pygeodesy.latDMS} or L{pygeodesy.lonDMS}.
1403 @kwarg joined: Separator to join the lat-, longitude and height strings (C{str}
1404 or C{None} or C{NN} for non-joined).
1405 @kwarg m: Optional unit of the height (C{str}), use C{None} to exclude height
1406 from the returned string.
1407 @kwarg prec_sep_s_D_M_S: Optional C{B{prec}ision}, C{B{sep}arator}, B{C{s_D}},
1408 B{C{s_M}}, B{C{s_S}} and B{C{s_DMS}} keyword arguments, see function
1409 L{pygeodesy.toDMS} for details.
1411 @return: This point in the specified C{B{form}at}, etc. (C{str} or a 2- or 3-tuple
1412 C{(lat_str, lon_str[, height_str])} if B{C{joined}} is C{NN} or C{None}).
1414 @see: Function L{pygeodesy.latDMS} or L{pygeodesy.lonDMS} for more details about
1415 keyword arguments C{B{form}at}, C{B{prec}ision}, C{B{sep}arator}, B{C{s_D}},
1416 B{C{s_M}}, B{C{s_S}} and B{C{s_DMS}}.
1417 '''
1418 t = (latDMS(self.lat, form=form, **prec_sep_s_D_M_S),
1419 lonDMS(self.lon, form=form, **prec_sep_s_D_M_S))
1420 if self.height and m is not None:
1421 t += (self.heightStr(m=m),)
1422 return joined.join(t) if joined else t
1424 def toVector(self, Vector=None, **Vector_kwds):
1425 '''Convert this point to a C{Vector} with the I{geocentric} C{(x, y, z)} (ECEF)
1426 coordinates, I{ignoring height}.
1428 @kwarg Vector: Optional class to return the I{geocentric} components (L{Vector3d})
1429 or C{None}.
1430 @kwarg Vector_kwds: Optionally, additional B{C{Vector}} keyword arguments,
1431 ignored if C{B{Vector} is None}.
1433 @return: A B{C{Vector}} instance or a L{Vector3Tuple}C{(x, y, z)} if C{B{Vector}
1434 is None}.
1436 @raise TypeError: Invalid B{C{Vector}} or B{C{Vector_kwds}}.
1438 @see: Methods C{toCartesian}, C{toNvector} and C{toVector3d}.
1439 '''
1440 return self._ecef9.toVector(Vector=Vector, **self._name1__(Vector_kwds))
1442 def toVector3d(self, norm=True, **Vector3d_kwds):
1443 '''Convert this point to a L{Vector3d} with the I{geocentric} C{(x, y, z)}
1444 (ECEF) coordinates, I{ignoring height}.
1446 @kwarg norm: If C{False}, don't normalize the coordinates (C{bool}).
1447 @kwarg Vector3d_kwds: Optional L{Vector3d} keyword arguments.
1449 @return: Named, unit vector or vector (L{Vector3d}).
1451 @raise TypeError: Invalid B{C{Vector3d_kwds}}.
1453 @see: Methods C{toCartesian}, C{toNvector} and C{toVector}.
1454 '''
1455 r = self.toVector(Vector=_MODS.vector3d.Vector3d, **Vector3d_kwds)
1456 if norm:
1457 r = r.unit(ll=self)
1458 return r
1460 def toWm(self, **toWm_kwds):
1461 '''Convert this point to a WM coordinate.
1463 @kwarg toWm_kwds: Optional L{pygeodesy.toWm} keyword arguments.
1465 @return: The WM coordinate (L{Wm}).
1467 @see: Function L{pygeodesy.toWm}.
1468 '''
1469 return _MODS.webmercator.toWm(self, **self._name1__(toWm_kwds))
1471 @deprecated_method
1472 def to3xyz(self): # PYCHOK no cover
1473 '''DEPRECATED, use property L{xyz} or method L{toNvector}, L{toVector},
1474 L{toVector3d} or perhaps (geocentric) L{toEcef}.'''
1475 return self.xyz # self.toVector()
1477# def _update(self, updated, *attrs, **setters):
1478# '''(INTERNAL) See C{_NamedBase._update}.
1479# '''
1480# if updated:
1481# self._rhumb3dict.clear()
1482# return _NamedBase._update(self, updated, *attrs, **setters)
1484 def vincentysTo(self, other, **radius_wrap):
1485 '''Compute the distance between this and an other point using U{Vincenty's
1486 <https://WikiPedia.org/wiki/Great-circle_distance>} spherical formula.
1488 @arg other: The other point (C{LatLon}).
1489 @kwarg radius_wrap: Optional C{B{radius}=R_M} and C{B{wrap}=False} for
1490 function L{pygeodesy.vincentys}, overriding the default
1491 C{mean radius} of this point's datum ellipsoid.
1493 @return: Distance (C{meter}, same units as B{C{radius}}).
1495 @raise TypeError: The B{C{other}} point is not C{LatLon}.
1497 @see: Function L{pygeodesy.vincentys} and methods L{cosineLawTo}, C{distanceTo*},
1498 L{equirectangularTo}, L{euclideanTo}, L{flatLocalTo} / L{hubenyTo},
1499 L{flatPolarTo}, L{haversineTo} and L{thomasTo}.
1500 '''
1501 return self._distanceTo(_formy.vincentys, other, **_xkwds(radius_wrap, radius=None))
1503 def _wrap_name2(self, wrap=False, **name):
1504 '''(INTERNAL) Return the C{wrap} and C{name} value.
1505 '''
1506 return wrap, (self._name__(name) if name else NN)
1508 @property_RO
1509 def xyz(self):
1510 '''Get the I{geocentric} C{(x, y, z)} coordinates (L{Vector3Tuple}C{(x, y, z)})
1511 '''
1512 return self._ecef9.xyz
1514 @property_RO
1515 def xyz3(self):
1516 '''Get the I{geocentric} C{(x, y, z)} coordinates as C{3-tuple}.
1517 '''
1518 return tuple(self.xyz)
1520 @Property_RO
1521 def xyzh(self):
1522 '''Get the I{geocentric} C{(x, y, z)} coordinates and height (L{Vector4Tuple}C{(x, y, z, h)})
1523 '''
1524 return self.xyz.to4Tuple(self.height)
1527class _toCartesian3(object): # see also .formy._idllmn6, .geodesicw._wargs, .vector2d._numpy
1528 '''(INTERNAL) Wrapper to convert 2 other points.
1529 '''
1530 @contextmanager # <https://www.Python.org/dev/peps/pep-0343/> Examples
1531 def __call__(self, p, p2, p3, wrap, **kwds):
1532 try:
1533 if wrap:
1534 p2, p3 = map1(_Wrap.point, p2, p3)
1535 kwds = _xkwds(kwds, wrap=wrap)
1536 yield (p. toCartesian().copy(name=_point_), # copy to rename
1537 p._toCartesianEcef(up=4, point2=p2),
1538 p._toCartesianEcef(up=4, point3=p3))
1539 except (AssertionError, TypeError, ValueError) as x: # Exception?
1540 raise _xError(x, point=p, point2=p2, point3=p3, **kwds)
1542_toCartesian3 = _toCartesian3() # PYCHOK singleton
1545def _latlonheight3(latlonh, height, wrap): # in .points.LatLon_.__init__
1546 '''(INTERNAL) Get 3-tuple C{(lat, lon, height)}.
1547 '''
1548 try:
1549 lat, lon = latlonh.lat, latlonh.lon
1550 height = _xattr(latlonh, height=height)
1551 except AttributeError:
1552 raise _IsnotError(_LatLon_, latlonh=latlonh)
1553 if wrap:
1554 lat, lon = _Wrap.latlon(lat, lon)
1555 return lat, lon, height
1558def latlon2n_xyz(lat_ll, lon=None, **name):
1559 '''Convert lat-, longitude to C{n-vector} (I{normal} to the earth's surface) X, Y and Z components.
1561 @arg lat_ll: Latitude (C{degrees}) or a C{LatLon} instance, L{LatLon2Tuple} or other C{LatLon*Tuple}.
1562 @kwarg lon: Longitude (C{degrees}), required if C{B{lon_ll} is degrees}, ignored otherwise.
1563 @kwarg name: Optional C{B{name}=NN} (C{str}).
1565 @return: A L{Vector3Tuple}C{(x, y, z)}.
1567 @see: Function L{philam2n_xyz}.
1569 @note: These are C{n-vector} x, y and z components, I{NOT geocentric} x, y and z (ECEF) coordinates!
1570 '''
1571 lat = lat_ll
1572 if lon is None:
1573 try:
1574 lat, lon = lat_ll.latlon
1575 except AttributeError:
1576 lat = lat_ll.lat
1577 lon = lat_ll.lon
1578 # Kenneth Gade eqn 3, but using right-handed
1579 # vector x -> 0°E,0°N, y -> 90°E,0°N, z -> 90°N
1580 sa, ca, sb, cb = sincos2d_(lat, lon)
1581 return Vector3Tuple(ca * cb, ca * sb, sa, **name)
1584def philam2n_xyz(phi_ll, lam=None, **name):
1585 '''Convert lat-, longitude to C{n-vector} (I{normal} to the earth's surface) X, Y and Z components.
1587 @arg phi_ll: Latitude (C{radians}) or a C{LatLon} instance with C{phi}, C{lam} or C{philam} attributes.
1588 @kwarg lam: Longitude (C{radians}), required if C{B{phi_ll} is radians}, ignored otherwise.
1589 @kwarg name: Optional name (C{str}).
1591 @return: A L{Vector3Tuple}C{(x, y, z)}.
1593 @see: Function L{latlon2n_xyz}.
1595 @note: These are C{n-vector} x, y and z components, I{NOT geocentric} x, y and z (ECEF) coordinates!
1596 '''
1597 phi = phi_ll
1598 if lam is None:
1599 try:
1600 phi, lam = phi_ll.philam
1601 except AttributeError:
1602 phi = phi_ll.phi
1603 lam = phi_ll.lam
1604 return latlon2n_xyz(degrees(phi), degrees(lam), **name)
1607def _trilaterate5(p1, d1, p2, d2, p3, d3, area=True, eps=EPS1, radius=R_M, wrap=False): # MCCABE 13
1608 '''(INTERNAL) Trilaterate three points by I{area overlap} or by I{perimeter intersection} of three circles.
1610 @note: The B{C{radius}} is needed only for C{n-vectorial} and C{sphericalTrigonometry.LatLon.distanceTo}
1611 methods and silently ignored by the C{ellipsoidalExact}, C{-GeodSolve}, C{-Karney} and
1612 C{-Vincenty.LatLon.distanceTo} methods.
1613 '''
1614 p2, p3, w = _unrollon3(p1, p2, p3, wrap)
1615 rw = dict(radius=radius, wrap=w)
1617 r1 = Distance_(distance1=d1)
1618 r2 = Distance_(distance2=d2)
1619 r3 = Distance_(distance3=d3)
1620 m = 0 if area else (r1 + r2 + r3)
1621 pc = 0
1622 t = []
1623 for _ in range(3):
1624 try: # intersection of circle (p1, r1) and (p2, r2)
1625 c1, c2 = p1.intersections2(r1, p2, r2, wrap=w)
1627 if area: # check overlap
1628 if c1 is c2: # abutting
1629 c = c1
1630 else: # nearest point on radical
1631 c = p3.nearestOn(c1, c2, within=True, wrap=w)
1632 d = r3 - p3.distanceTo(c, **rw)
1633 if d > eps: # sufficient overlap
1634 t.append((d, c))
1635 m = max(m, d)
1637 else: # check intersection
1638 for c in ((c1,) if c1 is c2 else (c1, c2)):
1639 d = fabs(r3 - p3.distanceTo(c, **rw))
1640 if d < eps: # below margin
1641 t.append((d, c))
1642 m = min(m, d)
1644 except IntersectionError as x:
1645 if _concentric_ in str(x): # XXX ConcentricError?
1646 pc += 1
1648 p1, r1, p2, r2, p3, r3 = p2, r2, p3, r3, p1, r1 # rotate
1650 if t: # get min, max, points and count ...
1651 t = tuple(sorted(t))
1652 n = len(t), # as 1-tuple
1653 # ... or for a single trilaterated result,
1654 # min *is* max, min- *is* maxPoint and n=1, 2 or 3
1655 return Trilaterate5Tuple(t[0] + t[-1] + n) # *(t[0] + ...)
1657 elif area and pc == 3: # all pairwise concentric ...
1658 r, p = min((r1, p1), (r2, p2), (r3, p3))
1659 m = max(r1, r2, r3)
1660 # ... return "smallest" point twice, the smallest
1661 # and largest distance and n=0 for concentric
1662 return Trilaterate5Tuple(float(r), p, float(m), p, 0)
1664 n, f = (_overlap_, max) if area else (_intersection_, min)
1665 t = _COMMASPACE_(_no_(n), '%s %.3g' % (typename(f), m))
1666 raise IntersectionError(area=area, eps=eps, wrap=wrap, txt=t)
1669__all__ += _ALL_DOCS(LatLonBase)
1671# **) MIT License
1672#
1673# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved.
1674#
1675# Permission is hereby granted, free of charge, to any person obtaining a
1676# copy of this software and associated documentation files (the "Software"),
1677# to deal in the Software without restriction, including without limitation
1678# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1679# and/or sell copies of the Software, and to permit persons to whom the
1680# Software is furnished to do so, subject to the following conditions:
1681#
1682# The above copyright notice and this permission notice shall be included
1683# in all copies or substantial portions of the Software.
1684#
1685# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1686# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1687# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1688# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1689# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1690# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1691# OTHER DEALINGS IN THE SOFTWARE.