Coverage for pygeodesy/ecef.py: 95%
453 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-05-04 12:01 -0400
« prev ^ index » next coverage.py v7.6.1, created at 2025-05-04 12:01 -0400
2# -*- coding: utf-8 -*-
4u'''I{Geocentric} Earth-Centered, Earth-Fixed (ECEF) coordinates.
6Geocentric conversions transcoded from I{Charles Karney}'s C++ class U{Geocentric
7<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Geocentric.html>}
8into pure Python class L{EcefKarney}, class L{EcefSudano} based on I{John Sudano}'s
9U{paper<https://www.ResearchGate.net/publication/
103709199_An_exact_conversion_from_an_Earth-centered_coordinate_system_to_latitude_longitude_and_altitude>},
11class L{EcefVeness} transcoded from I{Chris Veness}' JavaScript classes U{LatLonEllipsoidal,
12Cartesian<https://www.Movable-Type.co.UK/scripts/geodesy/docs/latlon-ellipsoidal.js.html>}, class L{EcefYou}
13implementing I{Rey-Jer You}'s U{transformations<https://www.ResearchGate.net/publication/240359424>} and
14classes L{EcefFarrell22} and L{EcefFarrell22} from I{Jay A. Farrell}'s U{Table 2.1 and 2.2
15<https://Books.Google.com/books?id=fW4foWASY6wC>}, page 29-30.
17Following is a copy of I{Karney}'s U{Detailed Description
18<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Geocentric.html>}.
20Convert between geodetic coordinates C{lat}-, C{lon}gitude and height C{h} (measured vertically
21from the surface of the ellipsoid) to geocentric C{x}, C{y} and C{z} coordinates, also known as
22I{Earth-Centered, Earth-Fixed} (U{ECEF<https://WikiPedia.org/wiki/ECEF>}).
24The origin of geocentric coordinates is at the center of the earth. The C{z} axis goes thru
25the North pole, C{lat} = 90°. The C{x} axis goes thru C{lat} = 0°, C{lon} = 0°.
27The I{local (cartesian) origin} is at (C{lat0}, C{lon0}, C{height0}). The I{local} C{x} axis points
28East, the I{local} C{y} axis points North and the I{local} C{z} axis is normal to the ellipsoid. The
29plane C{z = -height0} is tangent to the ellipsoid, hence the alternate name I{local tangent plane}.
31Forward conversion from geodetic to geocentric (ECEF) coordinates is straightforward.
33For the reverse transformation we use Hugues Vermeille's U{I{Direct transformation from geocentric
34coordinates to geodetic coordinates}<https://DOI.org/10.1007/s00190-002-0273-6>}, J. Geodesy
35(2002) 76, page 451-454.
37Several changes have been made to ensure that the method returns accurate results for all finite
38inputs (even if h is infinite). The changes are described in Appendix B of C. F. F. Karney
39U{I{Geodesics on an ellipsoid of revolution}<https://ArXiv.org/abs/1102.1215v1>}, Feb. 2011, 85,
40105-117 (U{preprint<https://ArXiv.org/abs/1102.1215v1>}). Vermeille similarly updated his method
41in U{I{An analytical method to transform geocentric into geodetic coordinates}
42<https://DOI.org/10.1007/s00190-010-0419-x>}, J. Geodesy (2011) 85, page 105-117. See U{Geocentric
43coordinates<https://GeographicLib.SourceForge.io/C++/doc/geocentric.html>} for more information.
45The errors in these routines are close to round-off. Specifically, for points within 5,000 Km of
46the surface of the ellipsoid (either inside or outside the ellipsoid), the error is bounded by 7
47nm (7 nanometers) for the WGS84 ellipsoid. See U{Geocentric coordinates
48<https://GeographicLib.SourceForge.io/C++/doc/geocentric.html>} for further information on the errors.
50@note: The C{reverse} methods of all C{Ecef...} classes return by default C{INT0} as the (geodetic)
51longitude for I{polar} ECEF location C{x == y == 0}. Use keyword argument C{lon00} or property
52C{lon00} to configure that value.
54@see: Module L{ltp} and class L{LocalCartesian}, a transcription of I{Charles Karney}'s C++ class
55U{LocalCartesian<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1LocalCartesian.html>},
56for conversion between geodetic and I{local cartesian} coordinates in a I{local tangent
57plane} as opposed to I{geocentric} (ECEF) ones.
58'''
60from pygeodesy.basics import copysign0, _isin, isscalar, issubclassof, neg, map1, \
61 _xinstanceof, _xsubclassof, typename # _args_kwds_names
62from pygeodesy.constants import EPS, EPS0, EPS02, EPS1, EPS2, EPS_2, INT0, PI, PI_2, \
63 _0_0, _0_0001, _0_01, _0_5, _1_0, _1_0_1T, _N_1_0, \
64 _2_0, _N_2_0, _3_0, _4_0, _6_0, _60_0, _90_0, _N_90_0, \
65 _100_0, _copysign_1_0, isnon0 # PYCHOK used!
66from pygeodesy.datums import _ellipsoidal_datum, _WGS84, a_f2Tuple, _EWGS84
67from pygeodesy.ecefLocals import _EcefLocal
68# from pygeodesy.ellipsoids import a_f2Tuple, _EWGS84 # from .datums
69from pygeodesy.errors import _IndexError, LenError, _ValueError, _TypesError, \
70 _xattr, _xdatum, _xkwds, _xkwds_get
71from pygeodesy.fmath import cbrt, fdot, hypot, hypot1, hypot2_, sqrt0
72from pygeodesy.fsums import Fsum, fsumf_, Fmt, unstr
73# from pygeodesy.internals import typename # from .basics
74from pygeodesy.interns import NN, _a_, _C_, _datum_, _ellipsoid_, _f_, _height_, \
75 _lat_, _lon_, _M_, _name_, _singular_, _SPACE_, \
76 _x_, _xyz_, _y_, _z_
77from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS
78from pygeodesy.named import _name__, _name1__, _NamedBase, _NamedTuple, _Pass, _xnamed
79from pygeodesy.namedTuples import LatLon2Tuple, LatLon3Tuple, \
80 PhiLam2Tuple, Vector3Tuple, Vector4Tuple
81from pygeodesy.props import deprecated_method, Property_RO, property_RO, \
82 property_ROver, property_doc_
83# from pygeodesy.streprs import Fmt, unstr # from .fsums
84from pygeodesy.units import _isRadius, Degrees, Height, Int, Lam, Lat, Lon, Meter, \
85 Phi, Scalar, Scalar_
86from pygeodesy.utily import atan1, atan1d, atan2, atan2d, degrees90, degrees180, \
87 sincos2, sincos2_, sincos2d, sincos2d_
88# from pygeodesy.vector3d import Vector3d # _MODS
90from math import cos, degrees, fabs, radians, sqrt
92__all__ = _ALL_LAZY.ecef
93__version__ = '25.04.28'
95_Ecef_ = 'Ecef'
96_prolate_ = 'prolate'
97_TRIPS = 33 # 8..9 sufficient, EcefSudano.reverse
98_xyz_y_z = _xyz_, _y_, _z_ # _args_kwds_names(_xyzn4)[:3]
101class EcefError(_ValueError):
102 '''An ECEF or C{Ecef*} related issue.
103 '''
104 pass
107class _EcefBase(_NamedBase):
108 '''(INTERNAL) Base class for L{EcefFarrell21}, L{EcefFarrell22}, L{EcefKarney},
109 L{EcefSudano}, L{EcefVeness} and L{EcefYou}.
110 '''
111 _datum = _WGS84
112 _E = _EWGS84
113 _isYou = False
114 _lon00 = INT0 # arbitrary, "polar" lon for LocalCartesian, Ltp
116 def __init__(self, a_ellipsoid=_EWGS84, f=None, lon00=INT0, **name):
117 '''New C{Ecef*} converter.
119 @arg a_ellipsoid: A (non-prolate) ellipsoid (L{Ellipsoid}, L{Ellipsoid2},
120 L{Datum} or L{a_f2Tuple}) or C{scalar} ellipsoid's
121 equatorial radius (C{meter}).
122 @kwarg f: C{None} or the ellipsoid flattening (C{scalar}), required
123 for C{scalar} B{C{a_ellipsoid}}, C{B{f}=0} represents a
124 sphere, negative B{C{f}} a prolate ellipsoid.
125 @kwarg lon00: An arbitrary, I{"polar"} longitude (C{degrees}), see the
126 C{reverse} method.
127 @kwarg name: Optional C{B{name}=NN} (C{str}).
129 @raise EcefError: If B{C{a_ellipsoid}} not L{Ellipsoid}, L{Ellipsoid2},
130 L{Datum} or L{a_f2Tuple} or C{scalar} or B{C{f}} not
131 C{scalar} or if C{scalar} B{C{a_ellipsoid}} not positive
132 or B{C{f}} not less than 1.0.
133 '''
134 try:
135 E = a_ellipsoid
136 if f is None:
137 pass
138 elif _isRadius(E) and isscalar(f):
139 E = a_f2Tuple(E, f)
140 else:
141 raise ValueError() # _invalid_
143 if not _isin(E, _EWGS84, _WGS84):
144 d = _ellipsoidal_datum(E, **name)
145 E = d.ellipsoid
146 if E.a < EPS or E.f > EPS1:
147 raise ValueError() # _invalid_
148 self._datum = d
149 self._E = E
151 except (TypeError, ValueError) as x:
152 t = unstr(self.classname, a=a_ellipsoid, f=f)
153 raise EcefError(_SPACE_(t, _ellipsoid_), cause=x)
155 if name:
156 self.name = name
157 if lon00 is not INT0:
158 self.lon00 = lon00
160 def __eq__(self, other):
161 '''Compare this and an other Ecef.
163 @arg other: The other ecef (C{Ecef*}).
165 @return: C{True} if equal, C{False} otherwise.
166 '''
167 return other is self or (isinstance(other, self.__class__) and
168 other.ellipsoid == self.ellipsoid)
170 @Property_RO
171 def datum(self):
172 '''Get the datum (L{Datum}).
173 '''
174 return self._datum
176 @Property_RO
177 def ellipsoid(self):
178 '''Get the ellipsoid (L{Ellipsoid} or L{Ellipsoid2}).
179 '''
180 return self._E
182 @Property_RO
183 def equatoradius(self):
184 '''Get the C{ellipsoid}'s equatorial radius, semi-axis (C{meter}).
185 '''
186 return self.ellipsoid.a
188 a = equatorialRadius = equatoradius # Karney property
190 @Property_RO
191 def flattening(self): # Karney property
192 '''Get the C{ellipsoid}'s flattening (C{scalar}), positive for
193 I{oblate}, negative for I{prolate} or C{0} for I{near-spherical}.
194 '''
195 return self.ellipsoid.f
197 f = flattening
199 def _forward(self, lat, lon, h, name, M=False, _philam=False): # in .ltp.LocalCartesian.forward and -.reset
200 '''(INTERNAL) Common for all C{Ecef*}.
201 '''
202 if _philam: # lat, lon in radians
203 sa, ca, sb, cb = sincos2_(lat, lon)
204 lat = Lat(degrees90( lat), Error=EcefError)
205 lon = Lon(degrees180(lon), Error=EcefError)
206 else:
207 sa, ca, sb, cb = sincos2d_(lat, lon)
209 E = self.ellipsoid
210 n = E.roc1_(sa, ca) if self._isYou else E.roc1_(sa)
211 z = (h + n * E.e21) * sa
212 x = (h + n) * ca
214 m = self._Matrix(sa, ca, sb, cb) if M else None
215 return Ecef9Tuple(x * cb, x * sb, z, lat, lon, h,
216 0, m, self.datum,
217 name=self._name__(name))
219 def forward(self, latlonh, lon=None, height=0, M=False, **name):
220 '''Convert from geodetic C{(lat, lon, height)} to geocentric C{(x, y, z)}.
222 @arg latlonh: Either a C{LatLon}, an L{Ecef9Tuple} or C{scalar}
223 latitude (C{degrees}).
224 @kwarg lon: Optional C{scalar} longitude for C{scalar} B{C{latlonh}}
225 (C{degrees}).
226 @kwarg height: Optional height (C{meter}), vertically above (or below)
227 the surface of the ellipsoid.
228 @kwarg M: Optionally, return the rotation L{EcefMatrix} (C{bool}).
229 @kwarg name: Optional C{B{name}=NN} (C{str}).
231 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
232 geocentric C{(x, y, z)} coordinates for the given geodetic ones
233 C{(lat, lon, height)}, case C{C} 0, optional C{M} (L{EcefMatrix})
234 and C{datum} if available.
236 @raise EcefError: If B{C{latlonh}} not C{LatLon}, L{Ecef9Tuple} or
237 C{scalar} or B{C{lon}} not C{scalar} for C{scalar}
238 B{C{latlonh}} or C{abs(lat)} exceeds 90°.
240 @note: Use method C{.forward_} to specify C{lat} and C{lon} in C{radians}
241 and avoid double angle conversions.
242 '''
243 llhn = _llhn4(latlonh, lon, height, **name)
244 return self._forward(*llhn, M=M)
246 def forward_(self, phi, lam, height=0, M=False, **name):
247 '''Like method C{.forward} except with geodetic lat- and longitude given
248 in I{radians}.
250 @arg phi: Latitude in I{radians} (C{scalar}).
251 @arg lam: Longitude in I{radians} (C{scalar}).
252 @kwarg height: Optional height (C{meter}), vertically above (or below)
253 the surface of the ellipsoid.
254 @kwarg M: Optionally, return the rotation L{EcefMatrix} (C{bool}).
255 @kwarg name: Optional C{B{name}=NN} (C{str}).
257 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)}
258 with C{lat} set to C{degrees90(B{phi})} and C{lon} to
259 C{degrees180(B{lam})}.
261 @raise EcefError: If B{C{phi}} or B{C{lam}} invalid or not C{scalar}.
262 '''
263 try: # like function C{_llhn4} below
264 plhn = Phi(phi), Lam(lam), Height(height), _name__(name)
265 except (TypeError, ValueError) as x:
266 raise EcefError(phi=phi, lam=lam, height=height, cause=x)
267 return self._forward(*plhn, M=M, _philam=True)
269 @property_ROver
270 def _Geocentrics(self):
271 '''(INTERNAL) Get the valid geocentric classes. I{once}.
272 '''
273 return (Ecef9Tuple, # overwrite property_ROver
274 _MODS.vector3d.Vector3d) # _MODS.cartesianBase.CartesianBase
276 @property
277 def lon00(self):
278 '''Get the I{"polar"} longitude (C{degrees}), see method C{reverse}.
279 '''
280 return self._lon00
282 @lon00.setter # PYCHOK setter!
283 def lon00(self, lon00):
284 '''Set the I{"polar"} longitude (C{degrees}), see method C{reverse}.
285 '''
286 self._lon00 = Degrees(lon00=lon00)
288 def _Matrix(self, sa, ca, sb, cb):
289 '''Creation a rotation matrix.
291 @arg sa: C{sin(phi)} (C{float}).
292 @arg ca: C{cos(phi)} (C{float}).
293 @arg sb: C{sin(lambda)} (C{float}).
294 @arg cb: C{cos(lambda)} (C{float}).
296 @return: An L{EcefMatrix}.
297 '''
298 return self._xnamed(EcefMatrix(sa, ca, sb, cb))
300 def _polon(self, y, x, R, **lon00_name):
301 '''(INTERNAL) Handle I{"polar"} longitude.
302 '''
303 return atan2d(y, x) if R else _xkwds_get(lon00_name, lon00=self.lon00)
305 def reverse(self, xyz, y=None, z=None, M=False, **lon00_name): # PYCHOK no cover
306 '''I{Must be overloaded}.'''
307 self._notOverloaded(xyz, y=y, z=z, M=M, **lon00_name)
309 def toStr(self, prec=9, **unused): # PYCHOK signature
310 '''Return this C{Ecef*} as a string.
312 @kwarg prec: Precision, number of decimal digits (0..9).
314 @return: This C{Ecef*} (C{str}).
315 '''
316 return self.attrs(_a_, _f_, _datum_, _name_, prec=prec) # _ellipsoid_
319class EcefFarrell21(_EcefBase):
320 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF)
321 coordinates based on I{Jay A. Farrell}'s U{Table 2.1<https://Books.Google.com/
322 books?id=fW4foWASY6wC>}, page 29.
323 '''
325 def reverse(self, xyz, y=None, z=None, M=None, **lon00_name): # PYCHOK unused M
326 '''Convert from geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)} using
327 I{Farrell}'s U{Table 2.1<https://Books.Google.com/books?id=fW4foWASY6wC>},
328 page 29, aka the I{Heikkinen application} of U{Ferrari's solution
329 <https://WikiPedia.org/wiki/Geographic_coordinate_conversion>}.
331 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x}
332 coordinate (C{meter}).
333 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}).
334 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}).
335 @kwarg M: I{Ignored}, rotation matrix C{M} not available.
336 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument
337 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude
338 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}.
340 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
341 geodetic coordinates C{(lat, lon, height)} for the given geocentric
342 ones C{(x, y, z)}, case C{C=1}, C{M=None} always and C{datum}
343 if available.
345 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or B{C{z}}
346 not C{scalar} for C{scalar} B{C{xyz}} or C{sqrt} domain or
347 zero division error.
349 @see: L{EcefFarrell22} and L{EcefVeness}.
350 '''
351 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name)
353 E = self.ellipsoid
354 a = E.a
355 a2 = E.a2
356 b2 = E.b2
357 e2 = E.e2
358 e2_ = E.e2abs * E.a2_b2 # (E.e * E.a_b)**2 = 0.0820944... WGS84
359 e4 = E.e4
361 try: # names as page 29
362 z2 = z**2
363 ez = z2 * (_1_0 - e2) # E.e2s2(z)
365 p = hypot(x, y)
366 p2 = p**2
367 G = p2 + ez - e2 * (a2 - b2) # p2 + ez - e4 * a2
368 F = b2 * z2 * 54
369 c = e4 * p2 * F / G**3
370 s = cbrt(sqrt(c * (c + _2_0)) + c + _1_0)
371 G *= fsumf_(s , _1_0, _1_0 / s) # k
372 P = F / (G**2 * _3_0)
373 Q = sqrt(_2_0 * e4 * P + _1_0)
374 Q1 = Q + _1_0
375 r0 = P * p * e2 / Q1 - sqrt(fsumf_(a2 * (Q1 / Q) * _0_5,
376 -P * ez / (Q * Q1),
377 -P * p2 * _0_5))
378 r = p + e2 * r0
379 v = b2 / (sqrt(r**2 + ez) * a) # z0 / z
381 h = hypot(r, z) * (_1_0 - v)
382 lat = atan1d((e2_ * v + _1_0) * z, p)
383 lon = self._polon(y, x, p, **lon00_name)
384 # note, phi and lam are swapped on page 29
386 except (ValueError, ZeroDivisionError) as X:
387 raise EcefError(x=x, y=y, z=z, cause=X)
389 return Ecef9Tuple(x, y, z, lat, lon, h,
390 1, None, self.datum,
391 name=self._name__(name))
394class EcefFarrell22(_EcefBase):
395 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF)
396 coordinates based on I{Jay A. Farrell}'s U{Table 2.2<https://Books.Google.com/
397 books?id=fW4foWASY6wC>}, page 30.
398 '''
400 def reverse(self, xyz, y=None, z=None, M=None, **lon00_name): # PYCHOK unused M
401 '''Convert from geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)} using
402 I{Farrell}'s U{Table 2.2<https://Books.Google.com/books?id=fW4foWASY6wC>},
403 page 30.
405 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x}
406 coordinate (C{meter}).
407 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}).
408 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}).
409 @kwarg M: I{Ignored}, rotation matrix C{M} not available.
410 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument
411 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude
412 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}.
414 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
415 geodetic coordinates C{(lat, lon, height)} for the given geocentric
416 ones C{(x, y, z)}, case C{C=1}, C{M=None} always and C{datum}
417 if available.
419 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or B{C{z}}
420 not C{scalar} for C{scalar} B{C{xyz}} or C{sqrt} domain or
421 zero division error.
423 @see: L{EcefFarrell21} and L{EcefVeness}.
424 '''
425 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name)
427 E = self.ellipsoid
428 a = E.a
429 b = E.b
431 try: # see EcefVeness.reverse
432 p = hypot(x, y)
433 lon = self._polon(y, x, p, **lon00_name)
435 s, c = sincos2(atan2(z * a, p * b)) # == _norm3
436 lat = atan1d(z + s**3 * b * E.e22,
437 p - c**3 * a * E.e2)
439 s, c = sincos2d(lat)
440 if c: # E.roc1_(s) = E.a / sqrt(1 - E.e2 * s**2)
441 h = p / c - (E.roc1_(s) if s else a)
442 else: # polar
443 h = fabs(z) - b
444 # note, phi and lam are swapped on page 30
446 except (ValueError, ZeroDivisionError) as e:
447 raise EcefError(x=x, y=y, z=z, cause=e)
449 return Ecef9Tuple(x, y, z, lat, lon, h,
450 1, None, self.datum,
451 name=self._name__(name))
454class EcefKarney(_EcefBase):
455 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF)
456 coordinates transcoded from I{Karney}'s C++ U{Geocentric<https://GeographicLib.SourceForge.io/
457 C++/doc/classGeographicLib_1_1Geocentric.html>} methods.
459 @note: On methods C{.forward} and C{.forwar_}, let C{v} be a unit vector located
460 at C{(lat, lon, h)}. We can express C{v} as column vectors in one of two
461 ways, C{v1} in East, North, Up (ENU) coordinates (where the components are
462 relative to a local coordinate system at C{C(lat0, lon0, h0)}) or as C{v0}
463 in geocentric C{x, y, z} coordinates. Then, M{v0 = M ⋅ v1} where C{M} is
464 the rotation matrix.
465 '''
467 @Property_RO
468 def hmax(self):
469 '''Get the distance or height limit (C{meter}, conventionally).
470 '''
471 return self.equatoradius / EPS_2 # self.equatoradius * _2_EPS, 12M lighyears
473 def reverse(self, xyz, y=None, z=None, M=False, **lon00_name):
474 '''Convert from geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)}.
476 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x}
477 coordinate (C{meter}).
478 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}).
479 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}).
480 @kwarg M: Optionally, return the rotation L{EcefMatrix} (C{bool}).
481 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument
482 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude
483 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}.
485 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
486 geodetic coordinates C{(lat, lon, height)} for the given geocentric
487 ones C{(x, y, z)}, case C{C}, optional C{M} (L{EcefMatrix}) and
488 C{datum} if available.
490 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or B{C{z}}
491 not C{scalar} for C{scalar} B{C{xyz}}.
493 @note: In general, there are multiple solutions and the result which minimizes
494 C{height} is returned, i.e., the C{(lat, lon)} corresponding to the
495 closest point on the ellipsoid. If there are still multiple solutions
496 with different latitudes (applies only if C{z} = 0), then the solution
497 with C{lat} > 0 is returned. If there are still multiple solutions with
498 different longitudes (applies only if C{x} = C{y} = 0), then C{lon00} is
499 returned. The returned C{lon} is in the range [−180°, 180°] and C{height}
500 is not below M{−E.a * (1 − E.e2) / sqrt(1 − E.e2 * sin(lat)**2)}. Like
501 C{forward} above, M{v1 = Transpose(M) ⋅ v0}.
502 '''
503 def _norm3(y, x):
504 h = hypot(y, x) # EPS0, EPS_2
505 return (y / h, x / h, h) if h > 0 else (_0_0, _1_0, h)
507 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name)
509 E = self.ellipsoid
510 f = E.f
512 sb, cb, R = _norm3(y, x)
513 h = hypot(R, z) # distance to earth center
514 if h > self.hmax: # PYCHOK no cover
515 # We are really far away (> 12M light years). Treat the earth
516 # as a point and h above as an acceptable approximation to the
517 # height. This avoids overflow, e.g., in the computation of d
518 # below. It's possible that h has overflowed to INF, that's OK.
519 # Treat finite x, y, but R overflows to +INF by scaling by 2.
520 sb, cb, R = _norm3(y * _0_5, x * _0_5)
521 sa, ca, _ = _norm3(z * _0_5, R)
522 C = 1
524 elif E.e4: # E.isEllipsoidal
525 # Treat prolate spheroids by swapping R and Z here and by
526 # switching the arguments to phi = atan2(...) at the end.
527 p = (R / E.a)**2
528 q = (z / E.a)**2 * E.e21
529 if f < 0:
530 p, q = q, p
531 r = fsumf_(p, q, -E.e4)
532 e = E.e4 * q
533 if e or r > 0:
534 # Avoid possible division by zero when r = 0 by multiplying
535 # equations for s and t by r^3 and r, respectively.
536 s = d = e * p / _4_0 # s = r^3 * s
537 u = r = r / _6_0
538 r2 = r**2
539 r3 = r2 * r
540 t3 = r3 + s
541 d *= t3 + r3
542 if d < 0:
543 # t is complex, but the way u is defined, the result is real.
544 # There are three possible cube roots. We choose the root
545 # which avoids cancellation. Note, d < 0 implies r < 0.
546 u += cos(atan2(sqrt(-d), -t3) / _3_0) * r * _2_0
547 else:
548 # Pick the sign on the sqrt to maximize abs(t3). This
549 # minimizes loss of precision due to cancellation. The
550 # result is unchanged because of the way the t is used
551 # in definition of u.
552 if d > 0:
553 t3 += copysign0(sqrt(d), t3) # t3 = (r * t)^3
554 # N.B. cbrt always returns the real root, cbrt(-8) = -2.
555 t = cbrt(t3) # t = r * t
556 if t: # t can be zero; but then r2 / t -> 0.
557 u = fsumf_(u, t, r2 / t)
558 v = sqrt(e + u**2) # guaranteed positive
559 # Avoid loss of accuracy when u < 0. Underflow doesn't occur in
560 # E.e4 * q / (v - u) because u ~ e^4 when q is small and u < 0.
561 u = (e / (v - u)) if u < 0 else (u + v) # u+v, guaranteed positive
562 # Need to guard against w going negative due to roundoff in u - q.
563 w = E.e2abs * (u - q) / (_2_0 * v)
564 # Rearrange expression for k to avoid loss of accuracy due to
565 # subtraction. Division by 0 not possible because u > 0, w >= 0.
566 k1 = k2 = (u / (sqrt(u + w**2) + w)) if w > 0 else sqrt(u)
567 if f < 0:
568 k1 -= E.e2
569 else:
570 k2 += E.e2
571 sa, ca, h = _norm3(z / k1, R / k2)
572 h *= k1 - E.e21
573 C = 2
575 else: # e = E.e4 * q == 0 and r <= 0
576 # This leads to k = 0 (oblate, equatorial plane) and k + E.e^2 = 0
577 # (prolate, rotation axis) and the generation of 0/0 in the general
578 # formulas for phi and h, using the general formula and division
579 # by 0 in formula for h. Handle this case by taking the limits:
580 # f > 0: z -> 0, k -> E.e2 * sqrt(q) / sqrt(E.e4 - p)
581 # f < 0: r -> 0, k + E.e2 -> -E.e2 * sqrt(q) / sqrt(E.e4 - p)
582 q = E.e4 - p
583 if f < 0:
584 p, q = q, p
585 e = E.a
586 else:
587 e = E.b2_a
588 sa, ca, h = _norm3(sqrt(q * E._1_e21), sqrt(p))
589 if z < 0: # for tiny negative z, not for prolate
590 sa = neg(sa)
591 h *= neg(e / E.e2abs)
592 C = 3
594 else: # E.e4 == 0, spherical case
595 # Dealing with underflow in the general case with E.e2 = 0 is
596 # difficult. Origin maps to North pole, same as with ellipsoid.
597 sa, ca, _ = _norm3((z if h else _1_0), R)
598 h -= E.a
599 C = 4
601 # lon00 <https://GitHub.com/mrJean1/PyGeodesy/issues/77>
602 lon = self._polon(sb, cb, R, **lon00_name)
603 m = self._Matrix(sa, ca, sb, cb) if M else None
604 return Ecef9Tuple(x, y, z, atan1d(sa, ca), lon, h,
605 C, m, self.datum, name=self._name__(name))
608class EcefSudano(_EcefBase):
609 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF) coordinates
610 based on I{John J. Sudano}'s U{paper<https://www.ResearchGate.net/publication/3709199>}.
611 '''
612 _tol = EPS2
614 def reverse(self, xyz, y=None, z=None, M=None, **lon00_name): # PYCHOK unused M
615 '''Convert from geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)} using
616 I{Sudano}'s U{iterative method<https://www.ResearchGate.net/publication/3709199>}.
618 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x}
619 coordinate (C{meter}).
620 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}).
621 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}).
622 @kwarg M: I{Ignored}, rotation matrix C{M} not available.
623 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument
624 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude
625 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}.
627 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with geodetic
628 coordinates C{(lat, lon, height)} for the given geocentric ones C{(x, y, z)},
629 iteration C{C}, C{M=None} always and C{datum} if available.
631 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or B{C{z}}
632 not C{scalar} for C{scalar} B{C{xyz}} or no convergence.
633 '''
634 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name)
636 E = self.ellipsoid
637 e = E.e2 * E.a
638 R = hypot(x, y) # Rh
639 d = e - R
641 lat = atan1d(z, R * E.e21)
642 sa, ca = sincos2d(fabs(lat))
643 # Sudano's Eq (A-6) and (A-7) refactored/reduced,
644 # replacing Rn from Eq (A-4) with n = E.a / ca:
645 # N = ca**2 * ((z + E.e2 * n * sa) * ca - R * sa)
646 # = ca**2 * (z * ca + E.e2 * E.a * sa - R * sa)
647 # = ca**2 * (z * ca + (E.e2 * E.a - R) * sa)
648 # D = ca**3 * (E.e2 * n / E.e2s2(sa)) - R
649 # = ca**2 * (E.e2 * E.a / E.e2s2(sa) - R / ca**2)
650 # N / D = (z * ca + (E.e2 * E.a - R) * sa) /
651 # (E.e2 * E.a / E.e2s2(sa) - R / ca**2)
652 tol = self.tolerance
653 _S2 = Fsum(sa).fsum2f_
654 for i in range(1, _TRIPS):
655 ca2 = _1_0 - sa**2
656 if ca2 < EPS_2: # PYCHOK no cover
657 ca = _0_0
658 break
659 ca = sqrt(ca2)
660 r = e / E.e2s2(sa) - R / ca2
661 if fabs(r) < EPS_2:
662 break
663 lat = None
664 sa, t = _S2(-z * ca / r, -d * sa / r)
665 if fabs(t) < tol:
666 break
667 else:
668 t = unstr(self.reverse, x=x, y=y, z=z)
669 raise EcefError(t, txt=Fmt.no_convergence(r, tol))
671 if lat is None:
672 lat = copysign0(atan1d(fabs(sa), ca), z)
673 lon = self._polon(y, x, R, **lon00_name)
675 h = fsumf_(R * ca, fabs(z * sa), -E.a * E.e2s(sa)) # use Veness'
676 # because Sudano's Eq (7) doesn't produce the correct height
677 # h = (fabs(z) + R - E.a * cos(a + E.e21) * sa / ca) / (ca + sa)
678 return Ecef9Tuple(x, y, z, lat, lon, h,
679 i, None, self.datum, # C=i, M=None
680 iteration=i, name=self._name__(name))
682 @property_doc_(''' the convergence tolerance (C{float}).''')
683 def tolerance(self):
684 '''Get the convergence tolerance (C{scalar}).
685 '''
686 return self._tol
688 @tolerance.setter # PYCHOK setter!
689 def tolerance(self, tol):
690 '''Set the convergence tolerance (C{scalar}).
692 @raise EcefError: Non-scalar or invalid B{C{tol}}.
693 '''
694 self._tol = Scalar_(tolerance=tol, low=EPS, Error=EcefError)
697class EcefVeness(_EcefBase):
698 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF) coordinates
699 transcoded from I{Chris Veness}' JavaScript classes U{LatLonEllipsoidal, Cartesian<https://
700 www.Movable-Type.co.UK/scripts/geodesy/docs/latlon-ellipsoidal.js.html>}.
702 @see: U{I{A Guide to Coordinate Systems in Great Britain}<https://www.OrdnanceSurvey.co.UK/
703 documents/resources/guide-coordinate-systems-great-britain.pdf>}, section I{B) Converting
704 between 3D Cartesian and ellipsoidal latitude, longitude and height coordinates}.
705 '''
707 def reverse(self, xyz, y=None, z=None, M=None, **lon00_name): # PYCHOK unused M
708 '''Conversion from geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)}
709 transcoded from I{Chris Veness}' U{JavaScript<https://www.Movable-Type.co.UK/
710 scripts/geodesy/docs/latlon-ellipsoidal.js.html>}.
712 Uses B. R. Bowring’s formulation for μm precision in concise form U{I{The accuracy
713 of geodetic latitude and height equations}<https://www.ResearchGate.net/publication/
714 233668213>}, Survey Review, Vol 28, 218, Oct 1985.
716 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x}
717 coordinate (C{meter}).
718 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}).
719 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}).
720 @kwarg M: I{Ignored}, rotation matrix C{M} not available.
721 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument
722 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude
723 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}.
725 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
726 geodetic coordinates C{(lat, lon, height)} for the given geocentric
727 ones C{(x, y, z)}, case C{C}, C{M=None} always and C{datum} if available.
729 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or B{C{z}}
730 not C{scalar} for C{scalar} B{C{xyz}}.
732 @see: Toms, Ralph M. U{I{An Efficient Algorithm for Geocentric to Geodetic
733 Coordinate Conversion}<https://www.OSTI.gov/scitech/biblio/110235>},
734 Sept 1995 and U{I{An Improved Algorithm for Geocentric to Geodetic
735 Coordinate Conversion}<https://www.OSTI.gov/scitech/servlets/purl/231228>},
736 Apr 1996, both from Lawrence Livermore National Laboratory (LLNL) and
737 Sudano, John J, U{I{An exact conversion from an Earth-centered coordinate
738 system to latitude longitude and altitude}<https://www.ResearchGate.net/
739 publication/3709199>}.
740 '''
741 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name)
743 E = self.ellipsoid
744 a = E.a
746 p = hypot(x, y) # distance from minor axis
747 r = hypot(p, z) # polar radius
748 if min(p, r) > EPS0:
749 b = E.b * E.e22
750 # parametric latitude (Bowring eqn 17, replaced)
751 t = (E.b * z) / (a * p) * (_1_0 + b / r)
752 c = _1_0 / hypot1(t)
753 s = c * t
754 # geodetic latitude (Bowring eqn 18)
755 lat = atan1d(z + s**3 * b,
756 p - c**3 * a * E.e2)
758 # height above ellipsoid (Bowring eqn 7)
759 sa, ca = sincos2d(lat)
760# r = a / E.e2s(sa) # length of normal terminated by minor axis
761# h = p * ca + z * sa - (a * a / r)
762 h = fsumf_(p * ca, z * sa, -a * E.e2s(sa))
763 C = 1
765 # see <https://GIS.StackExchange.com/questions/28446>
766 elif p > EPS: # lat arbitrarily zero, equatorial lon
767 C, lat, h = 2, _0_0, (p - a)
769 else: # polar lat, lon arbitrarily lon00
770 C, lat, h = 3, (_N_90_0 if z < 0 else _90_0), (fabs(z) - E.b)
772 lon = self._polon(y, x, p, **lon00_name)
773 return Ecef9Tuple(x, y, z, lat, lon, h,
774 C, None, self.datum, # M=None
775 name=self._name__(name))
778class EcefYou(_EcefBase):
779 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF) coordinates
780 using I{Rey-Jer You}'s U{transformation<https://www.ResearchGate.net/publication/240359424>}
781 for I{non-prolate} ellipsoids.
783 @see: Featherstone, W.E., Claessens, S.J. U{I{Closed-form transformation between geodetic and
784 ellipsoidal coordinates}<https://Espace.Curtin.edu.AU/bitstream/handle/20.500.11937/
785 11589/115114_9021_geod2ellip_final.pdf>} Studia Geophysica et Geodaetica, 2008, 52,
786 pages 1-18 and U{PyMap3D <https://PyPI.org/project/pymap3d>}.
787 '''
788 _isYou = True
790 def __init__(self, a_ellipsoid=_EWGS84, f=None, **lon00_name): # PYCHOK signature
791 _EcefBase.__init__(self, a_ellipsoid, f=f, **lon00_name) # inherited documentation
792 self._ee2 = EcefYou._ee2(self.ellipsoid)
794 @staticmethod
795 def _ee2(E):
796 e2 = E.a2 - E.b2
797 if e2 < 0 or E.f < 0:
798 raise EcefError(ellipsoid=E, txt=_prolate_)
799 return sqrt0(e2), e2
801 def reverse(self, xyz, y=None, z=None, M=None, **lon00_name): # PYCHOK unused M
802 '''Convert geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)}
803 using I{Rey-Jer You}'s transformation.
805 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x}
806 coordinate (C{meter}).
807 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}).
808 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}).
809 @kwarg M: I{Ignored}, rotation matrix C{M} not available.
810 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument
811 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude
812 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}.
814 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
815 geodetic coordinates C{(lat, lon, height)} for the given geocentric
816 ones C{(x, y, z)}, case C{C=1}, C{M=None} always and C{datum} if
817 available.
819 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or
820 B{C{z}} not C{scalar} for C{scalar} B{C{xyz}} or the
821 ellipsoid is I{prolate}.
822 '''
823 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name)
824 q = hypot(x, y) # R
826 E = self.ellipsoid
827 e, e2 = self._ee2
829 u = hypot2_(x, y, z) - e2
830 u += hypot(u, e * z * _2_0)
831 u *= _0_5
832 if u > EPS02:
833 u = sqrt(u)
834 p = hypot(u, e)
835 B = atan1(p * z, u * q) # beta0 = atan(p / u * z / q)
836 sB, cB = sincos2(B)
837 if cB and sB:
838 p *= E.a
839 d = (p / cB - e2 * cB) / sB
840 if isnon0(d):
841 B += fsumf_(u * E.b, -p, e2) / d
842 sB, cB = sincos2(B)
843 elif u < (-EPS2):
844 raise EcefError(x=x, y=y, z=z, u=u, txt=_singular_)
845 else:
846 sB, cB = _copysign_1_0(z), _0_0
848 lat = atan1d(E.a * sB, E.b * cB) # atan(E.a_b * tan(B))
849 lon = self._polon(y, x, q, **lon00_name)
851 h = hypot(z - E.b * sB, q - E.a * cB)
852 if hypot2_(x, y, z * E.a_b) < E.a2:
853 h = neg(h) # inside ellipsoid
854 return Ecef9Tuple(x, y, z, lat, lon, h,
855 1, None, self.datum, # C=1, M=None
856 name=self._name__(name))
859class EcefMatrix(_NamedTuple):
860 '''A rotation matrix known as I{East-North-Up (ENU) to ECEF}.
862 @see: U{From ENU to ECEF<https://WikiPedia.org/wiki/
863 Geographic_coordinate_conversion#From_ECEF_to_ENU>} and
864 U{Issue #74<https://Github.com/mrJean1/PyGeodesy/issues/74>}.
865 '''
866 _Names_ = ('_0_0_', '_0_1_', '_0_2_', # row-order
867 '_1_0_', '_1_1_', '_1_2_',
868 '_2_0_', '_2_1_', '_2_2_')
869 _Units_ = (Scalar,) * len(_Names_)
871 def _validate(self, **unused): # PYCHOK unused
872 '''(INTERNAL) Allow C{_Names_} with leading underscore.
873 '''
874 _NamedTuple._validate(self, underOK=True)
876 def __new__(cls, sa, ca, sb, cb, *_more):
877 '''New L{EcefMatrix} matrix.
879 @arg sa: C{sin(phi)} (C{float}).
880 @arg ca: C{cos(phi)} (C{float}).
881 @arg sb: C{sin(lambda)} (C{float}).
882 @arg cb: C{cos(lambda)} (C{float}).
883 @arg _more: (INTERNAL) from C{.multiply}.
885 @raise EcefError: If B{C{sa}}, B{C{ca}}, B{C{sb}} or
886 B{C{cb}} outside M{[-1.0, +1.0]}.
887 '''
888 t = sa, ca, sb, cb
889 if _more: # all 9 matrix elements ...
890 t += _more # ... from .multiply
892 elif max(map(fabs, t)) > _1_0:
893 raise EcefError(unstr(EcefMatrix, *t))
895 else: # build matrix from the following quaternion operations
896 # qrot(lam, [0,0,1]) * qrot(phi, [0,-1,0]) * [1,1,1,1]/2
897 # or
898 # qrot(pi/2 + lam, [0,0,1]) * qrot(-pi/2 + phi, [-1,0,0])
899 # where
900 # qrot(t,v) = [cos(t/2), sin(t/2)*v[1], sin(t/2)*v[2], sin(t/2)*v[3]]
902 # Local X axis (East) in geocentric coords
903 # M[0] = -slam; M[3] = clam; M[6] = 0;
904 # Local Y axis (North) in geocentric coords
905 # M[1] = -clam * sphi; M[4] = -slam * sphi; M[7] = cphi;
906 # Local Z axis (Up) in geocentric coords
907 # M[2] = clam * cphi; M[5] = slam * cphi; M[8] = sphi;
908 t = (-sb, -cb * sa, cb * ca,
909 cb, -sb * sa, sb * ca,
910 _0_0, ca, sa)
912 return _NamedTuple.__new__(cls, *t)
914 def column(self, column):
915 '''Get this matrix' B{C{column}} 0, 1 or 2 as C{3-tuple}.
916 '''
917 if 0 <= column < 3:
918 return self[column::3]
919 raise _IndexError(column=column)
921 def copy(self, **unused): # PYCHOK signature
922 '''Make a shallow or deep copy of this instance.
924 @return: The copy (C{This class} or subclass thereof).
925 '''
926 return self.classof(*self)
928 __copy__ = __deepcopy__ = copy
930 @Property_RO
931 def matrix3(self):
932 '''Get this matrix' rows (C{3-tuple} of 3 C{3-tuple}s).
933 '''
934 return tuple(map(self.row, range(3)))
936 @Property_RO
937 def matrixTransposed3(self):
938 '''Get this matrix' I{Transposed} rows (C{3-tuple} of 3 C{3-tuple}s).
939 '''
940 return tuple(map(self.column, range(3)))
942 def multiply(self, other):
943 '''Matrix multiply M{M0' ⋅ M} this matrix I{Transposed}
944 with an other matrix.
946 @arg other: The other matrix (L{EcefMatrix}).
948 @return: The matrix product (L{EcefMatrix}).
950 @raise TypeError: If B{C{other}} is not an L{EcefMatrix}.
951 '''
952 _xinstanceof(EcefMatrix, other=other)
953 # like LocalCartesian.MatrixMultiply, C{self.matrixTransposed3 X other.matrix3}
954 # <https://GeographicLib.SourceForge.io/C++/doc/LocalCartesian_8cpp_source.html>
955 # X = (fdot(self.column(r), *other.column(c)) for r in (0,1,2) for c in (0,1,2))
956 X = (fdot(self[r::3], *other[c::3]) for r in range(3) for c in range(3))
957 return _xnamed(EcefMatrix(*X), typename(EcefMatrix.multiply))
959 def rotate(self, xyz, *xyz0):
960 '''Forward rotation M{M0' ⋅ ([x, y, z] - [x0, y0, z0])'}.
962 @arg xyz: Local C{(x, y, z)} coordinates (C{3-tuple}).
963 @arg xyz0: Optional, local C{(x0, y0, z0)} origin (C{3-tuple}).
965 @return: Rotated C{(x, y, z)} location (C{3-tuple}).
967 @raise LenError: Unequal C{len(B{xyz})} and C{len(B{xyz0})}.
968 '''
969 if xyz0:
970 if len(xyz0) != len(xyz):
971 raise LenError(self.rotate, xyz0=len(xyz0), xyz=len(xyz))
972 xyz = tuple(c - c0 for c, c0 in zip(xyz, xyz0))
974 # x' = M[0] * x + M[3] * y + M[6] * z
975 # y' = M[1] * x + M[4] * y + M[7] * z
976 # z' = M[2] * x + M[5] * y + M[8] * z
977 return (fdot(xyz, *self[0::3]), # .column(0)
978 fdot(xyz, *self[1::3]), # .column(1)
979 fdot(xyz, *self[2::3])) # .column(2)
981 def row(self, row):
982 '''Get this matrix' B{C{row}} 0, 1 or 2 as C{3-tuple}.
983 '''
984 if 0 <= row < 3:
985 r = row * 3
986 return self[r:r+3]
987 raise _IndexError(row=row)
989 def unrotate(self, xyz, *xyz0):
990 '''Inverse rotation M{[x0, y0, z0] + M0 ⋅ [x,y,z]'}.
992 @arg xyz: Local C{(x, y, z)} coordinates (C{3-tuple}).
993 @arg xyz0: Optional, local C{(x0, y0, z0)} origin (C{3-tuple}).
995 @return: Unrotated C{(x, y, z)} location (C{3-tuple}).
997 @raise LenError: Unequal C{len(B{xyz})} and C{len(B{xyz0})}.
998 '''
999 if xyz0:
1000 if len(xyz0) != len(xyz):
1001 raise LenError(self.unrotate, xyz0=len(xyz0), xyz=len(xyz))
1002 _xyz = _1_0_1T + xyz
1003 # x' = x0 + M[0] * x + M[1] * y + M[2] * z
1004 # y' = y0 + M[3] * x + M[4] * y + M[5] * z
1005 # z' = z0 + M[6] * x + M[7] * y + M[8] * z
1006 xyz_ = (fdot(_xyz, xyz0[0], *self[0:3]), # .row(0)
1007 fdot(_xyz, xyz0[1], *self[3:6]), # .row(1)
1008 fdot(_xyz, xyz0[2], *self[6:9])) # .row(2)
1009 else:
1010 # x' = M[0] * x + M[1] * y + M[2] * z
1011 # y' = M[3] * x + M[4] * y + M[5] * z
1012 # z' = M[6] * x + M[7] * y + M[8] * z
1013 xyz_ = (fdot(xyz, *self[0:3]), # .row(0)
1014 fdot(xyz, *self[3:6]), # .row(1)
1015 fdot(xyz, *self[6:9])) # .row(2)
1016 return xyz_
1019class Ecef9Tuple(_NamedTuple, _EcefLocal):
1020 '''9-Tuple C{(x, y, z, lat, lon, height, C, M, datum)} with I{geocentric} C{x},
1021 C{y} and C{z} plus I{geodetic} C{lat}, C{lon} and C{height}, case C{C} (see
1022 the C{Ecef*.reverse} methods) and optionally, rotation matrix C{M} (L{EcefMatrix})
1023 and C{datum}, with C{lat} and C{lon} in C{degrees} and C{x}, C{y}, C{z} and
1024 C{height} in C{meter}, conventionally.
1025 '''
1026 _Names_ = (_x_, _y_, _z_, _lat_, _lon_, _height_, _C_, _M_, _datum_)
1027 _Units_ = ( Meter, Meter, Meter, Lat, Lon, Height, Int, _Pass, _Pass)
1029 @property_ROver
1030 def _CartesianBase(self):
1031 '''(INTERNAL) Get class C{CartesianBase}, I{once}.
1032 '''
1033 return _MODS.cartesianBase.CartesianBase # overwrite property_ROver
1035 @deprecated_method
1036 def convertDatum(self, datum2): # for backward compatibility
1037 '''DEPRECATED, use method L{toDatum}.'''
1038 return self.toDatum(datum2)
1040 @property_RO
1041 def _ecef9(self): # in ._EcefLocal._Ltp_ecef2local
1042 return self
1044 @Property_RO
1045 def lam(self):
1046 '''Get the longitude in C{radians} (C{float}).
1047 '''
1048 return self.philam.lam
1050 @Property_RO
1051 def lamVermeille(self):
1052 '''Get the longitude in C{radians} M{[-PI*3/2..+PI*3/2]} after U{Vermeille
1053 <https://Search.ProQuest.com/docview/639493848>} (2004), page 95.
1055 @see: U{Karney<https://GeographicLib.SourceForge.io/C++/doc/geocentric.html>},
1056 U{Vermeille<https://Search.ProQuest.com/docview/847292978>} 2011, pp 112-113, 116
1057 and U{Featherstone, et.al.<https://Search.ProQuest.com/docview/872827242>}, page 7.
1058 '''
1059 x, y = self.x, self.y
1060 if y > EPS0:
1061 r = atan2(x, hypot(y, x) + y) * _N_2_0 + PI_2
1062 elif y < -EPS0:
1063 r = atan2(x, hypot(y, x) - y) * _2_0 - PI_2
1064 else: # y == 0
1065 r = PI if x < 0 else _0_0
1066 return Lam(Vermeille=r)
1068 @Property_RO
1069 def latlon(self):
1070 '''Get the lat-, longitude in C{degrees} (L{LatLon2Tuple}C{(lat, lon)}).
1071 '''
1072 return LatLon2Tuple(self.lat, self.lon, name=self.name)
1074 @Property_RO
1075 def latlonheight(self):
1076 '''Get the lat-, longitude in C{degrees} and height (L{LatLon3Tuple}C{(lat, lon, height)}).
1077 '''
1078 return self.latlon.to3Tuple(self.height)
1080 @Property_RO
1081 def latlonheightdatum(self):
1082 '''Get the lat-, longitude in C{degrees} with height and datum (L{LatLon4Tuple}C{(lat, lon, height, datum)}).
1083 '''
1084 return self.latlonheight.to4Tuple(self.datum)
1086 @Property_RO
1087 def latlonVermeille(self):
1088 '''Get the latitude and I{Vermeille} longitude in C{degrees [-225..+225]} (L{LatLon2Tuple}C{(lat, lon)}).
1090 @see: Property C{lonVermeille}.
1091 '''
1092 return LatLon2Tuple(self.lat, self.lonVermeille, name=self.name)
1094 @Property_RO
1095 def lonVermeille(self):
1096 '''Get the longitude in C{degrees [-225..+225]} after U{Vermeille
1097 <https://Search.ProQuest.com/docview/639493848>} 2004, p 95.
1099 @see: Property C{lamVermeille}.
1100 '''
1101 return Lon(Vermeille=degrees(self.lamVermeille))
1103 @Property_RO
1104 def phi(self):
1105 '''Get the latitude in C{radians} (C{float}).
1106 '''
1107 return self.philam.phi
1109 @Property_RO
1110 def philam(self):
1111 '''Get the lat-, longitude in C{radians} (L{PhiLam2Tuple}C{(phi, lam)}).
1112 '''
1113 return PhiLam2Tuple(radians(self.lat), radians(self.lon), name=self.name)
1115 @Property_RO
1116 def philamheight(self):
1117 '''Get the lat-, longitude in C{radians} and height (L{PhiLam3Tuple}C{(phi, lam, height)}).
1118 '''
1119 return self.philam.to3Tuple(self.height)
1121 @Property_RO
1122 def philamheightdatum(self):
1123 '''Get the lat-, longitude in C{radians} with height and datum (L{PhiLam4Tuple}C{(phi, lam, height, datum)}).
1124 '''
1125 return self.philamheight.to4Tuple(self.datum)
1127 @Property_RO
1128 def philamVermeille(self):
1129 '''Get the latitude and I{Vermeille} longitude in C{radians [-PI*3/2..+PI*3/2]} (L{PhiLam2Tuple}C{(phi, lam)}).
1131 @see: Property C{lamVermeille}.
1132 '''
1133 return PhiLam2Tuple(radians(self.lat), self.lamVermeille, name=self.name)
1135 phiVermeille = phi
1137 def toCartesian(self, Cartesian=None, **Cartesian_kwds):
1138 '''Return the geocentric C{(x, y, z)} coordinates as an ellipsoidal or spherical
1139 C{Cartesian}.
1141 @kwarg Cartesian: Optional class to return C{(x, y, z)} (L{ellipsoidalKarney.Cartesian},
1142 L{ellipsoidalNvector.Cartesian}, L{ellipsoidalVincenty.Cartesian},
1143 L{sphericalNvector.Cartesian} or L{sphericalTrigonometry.Cartesian})
1144 or C{None}.
1145 @kwarg Cartesian_kwds: Optionally, additional B{C{Cartesian}} keyword arguments, ignored
1146 if C{B{Cartesian} is None}.
1148 @return: A B{C{Cartesian}} instance or a L{Vector4Tuple}C{(x, y, z, h)} if C{B{Cartesian}
1149 is None}.
1151 @raise TypeError: Invalid B{C{Cartesian}} or B{C{Cartesian_kwds}} item.
1152 '''
1153 if _isin(Cartesian, None, Vector4Tuple):
1154 r = self.xyzh
1155 elif Cartesian is Vector3Tuple:
1156 r = self.xyz
1157 else:
1158 _xsubclassof(self._CartesianBase, Cartesian=Cartesian)
1159 r = Cartesian(self, **_name1__(Cartesian_kwds, _or_nameof=self))
1160 return r
1162 def toDatum(self, datum2, **name):
1163 '''Convert this C{Ecef9Tuple} to an other datum.
1165 @arg datum2: Datum to convert I{to} (L{Datum}).
1166 @kwarg name: Optional C{B{name}=NN} (C{str}).
1168 @return: The converted 9-Tuple (C{Ecef9Tuple}).
1170 @raise TypeError: The B{C{datum2}} is not a L{Datum}.
1171 '''
1172 n = _name__(name, _or_nameof=self)
1173 if _isin(self.datum, None, datum2): # PYCHOK _Names_
1174 r = self.copy(name=n)
1175 else:
1176 c = self._CartesianBase(self, datum=self.datum, name=n) # PYCHOK _Names_
1177 # c.toLatLon converts datum, x, y, z, lat, lon, etc.
1178 # and returns another Ecef9Tuple iff LatLon is None
1179 r = c.toLatLon(datum=datum2, LatLon=None)
1180 return r
1182 def toLatLon(self, LatLon=None, **LatLon_kwds):
1183 '''Return the geodetic C{(lat, lon, height[, datum])} coordinates.
1185 @kwarg LatLon: Optional class to return C{(lat, lon, height[, datum])} or C{None}.
1186 @kwarg LatLon_kwds: Optional B{C{height}}, B{C{datum}} and other B{C{LatLon}}
1187 keyword arguments.
1189 @return: A B{C{LatLon}} instance or if C{B{LatLon} is None}, a L{LatLon4Tuple}C{(lat,
1190 lon, height, datum)} or L{LatLon3Tuple}C{(lat, lon, height)} if C{datum} is
1191 specified or not.
1193 @raise TypeError: Invalid B{C{LatLon}} or B{C{LatLon_kwds}} item.
1194 '''
1195 lat, lon, D = self.lat, self.lon, self.datum # PYCHOK Ecef9Tuple
1196 kwds = _name1__(LatLon_kwds, _or_nameof=self)
1197 kwds = _xkwds(kwds, height=self.height, datum=D) # PYCHOK Ecef9Tuple
1198 d = kwds.get(_datum_, LatLon)
1199 if LatLon is None:
1200 r = LatLon3Tuple(lat, lon, kwds[_height_], name=kwds[_name_])
1201 if d is not None:
1202 # assert d is not LatLon
1203 r = r.to4Tuple(d) # checks type(d)
1204 else:
1205 if d is None:
1206 _ = kwds.pop(_datum_) # remove None datum
1207 r = LatLon(lat, lon, **kwds)
1208 _xdatum(_xattr(r, datum=D), D)
1209 return r
1211 def toVector(self, Vector=None, **Vector_kwds):
1212 '''Return these geocentric C{(x, y, z)} coordinates as vector.
1214 @kwarg Vector: Optional vector class to return C{(x, y, z)} or C{None}.
1215 @kwarg Vector_kwds: Optional, additional B{C{Vector}} keyword arguments,
1216 ignored if C{B{Vector} is None}.
1218 @return: A B{C{Vector}} instance or a L{Vector3Tuple}C{(x, y, z)} if
1219 C{B{Vector} is None}.
1221 @raise TypeError: Invalid B{C{Vector}} or B{C{Vector_kwds}} item.
1223 @see: Propertes C{xyz} and C{xyzh}
1224 '''
1225 return self.xyz if Vector is None else Vector(
1226 *self.xyz, **_name1__(Vector_kwds, _or_nameof=self)) # PYCHOK Ecef9Tuple
1228# def _T_x_M(self, T):
1229# '''(INTERNAL) Update M{self.M = T.multiply(self.M)}.
1230# '''
1231# return self.dup(M=T.multiply(self.M))
1233 @Property_RO
1234 def xyz(self):
1235 '''Get the geocentric C{(x, y, z)} coordinates (L{Vector3Tuple}C{(x, y, z)}).
1236 '''
1237 return Vector3Tuple(self.x, self.y, self.z, name=self.name)
1239 @Property_RO
1240 def xyzh(self):
1241 '''Get the geocentric C{(x, y, z)} coordinates and C{height} (L{Vector4Tuple}C{(x, y, z, h)})
1242 '''
1243 return self.xyz.to4Tuple(self.height)
1246def _4Ecef(this, Ecef): # in .datums.Datum.ecef, .ellipsoids.Ellipsoid.ecef
1247 '''Return an ECEF converter for C{this} L{Datum} or L{Ellipsoid}.
1248 '''
1249 if Ecef is None:
1250 Ecef = EcefKarney
1251 else:
1252 _xinstanceof(*_Ecefs, Ecef=Ecef)
1253 return Ecef(this, name=this.name)
1256def _llhn4(latlonh, lon, height, suffix=NN, Error=EcefError, **name): # in .ltp
1257 '''(INTERNAL) Get a C{(lat, lon, h, name)} 4-tuple.
1258 '''
1259 try:
1260 lat, lon = latlonh.lat, latlonh.lon
1261 h = _xattr(latlonh, height=_xattr(latlonh, h=height))
1262 n = _name__(name, _or_nameof=latlonh) # == latlonh._name__(name)
1263 except AttributeError:
1264 lat, h, n = latlonh, height, _name__(**name)
1265 try:
1266 return Lat(lat), Lon(lon), Height(h), n
1267 except (TypeError, ValueError) as x:
1268 t = _lat_, _lon_, _height_
1269 if suffix:
1270 t = (_ + suffix for _ in t)
1271 d = dict(zip(t, (lat, lon, h)))
1272 raise Error(cause=x, **d)
1275def _xEcef(Ecef): # PYCHOK .latlonBase
1276 '''(INTERNAL) Validate B{C{Ecef}} I{class}.
1277 '''
1278 if issubclassof(Ecef, _EcefBase):
1279 return Ecef
1280 raise _TypesError(_Ecef_, Ecef, *_Ecefs)
1283# kwd lon00 unused but will throw a TypeError if misspelled, etc.
1284def _xyzn4(xyz, y, z, Types, Error=EcefError, lon00=0, # PYCHOK unused
1285 _xyz_y_z_names=_xyz_y_z, **name): # in .ltp
1286 '''(INTERNAL) Get an C{(x, y, z, name)} 4-tuple.
1287 '''
1288 try:
1289 n = _name__(name, _or_nameof=xyz) # == xyz._name__(name)
1290 try:
1291 t = xyz.x, xyz.y, xyz.z, n
1292 if not isinstance(xyz, Types):
1293 raise _TypesError(_xyz_y_z_names[0], xyz, *Types)
1294 except AttributeError:
1295 t = map1(float, xyz, y, z) + (n,)
1296 except (TypeError, ValueError) as x:
1297 d = dict(zip(_xyz_y_z_names, (xyz, y, z)))
1298 raise Error(cause=x, **d)
1299 return t
1300# assert _xyz_y_z == _args_kwds_names(_xyzn4)[:3]
1303_Ecefs = (EcefKarney, EcefSudano, EcefVeness, EcefYou,
1304 EcefFarrell21, EcefFarrell22)
1305__all__ += _ALL_DOCS(_EcefBase)
1307# **) MIT License
1308#
1309# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved.
1310#
1311# Permission is hereby granted, free of charge, to any person obtaining a
1312# copy of this software and associated documentation files (the "Software"),
1313# to deal in the Software without restriction, including without limitation
1314# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1315# and/or sell copies of the Software, and to permit persons to whom the
1316# Software is furnished to do so, subject to the following conditions:
1317#
1318# The above copyright notice and this permission notice shall be included
1319# in all copies or substantial portions of the Software.
1320#
1321# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1322# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1323# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1324# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1325# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1326# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1327# OTHER DEALINGS IN THE SOFTWARE.