Coverage for pygeodesy/ecef.py: 95%
456 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'''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 a_f2Tuple, _ellipsoidal_datum, _WGS84, _EWGS84
67# from pygeodesy.ellipsoids import a_f2Tuple, _EWGS84 # from .datums
68from pygeodesy.errors import _IndexError, LenError, _ValueError, _TypesError, \
69 _xattr, _xdatum, _xkwds, _xkwds_get
70from pygeodesy.fmath import cbrt, fdot, Fpowers, hypot, hypot1, hypot2_, sqrt0
71from pygeodesy.fsums import Fsum, fsumf_, Fmt, unstr
72# from pygeodesy.internals import typename # from .basics
73from pygeodesy.interns import NN, _a_, _C_, _datum_, _ellipsoid_, _f_, _height_, \
74 _lat_, _lon_, _M_, _name_, _singular_, _SPACE_, \
75 _x_, _xyz_, _y_, _z_
76from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS
77from pygeodesy.named import _name__, _name1__, _NamedBase, _NamedLocal, \
78 _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.24'
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 _lon00 = INT0 # arbitrary, "polar" lon for LocalCartesian, Ltp
115 def __init__(self, a_ellipsoid=_EWGS84, f=None, lon00=INT0, **name):
116 '''New C{Ecef*} converter.
118 @arg a_ellipsoid: A (non-prolate) ellipsoid (L{Ellipsoid}, L{Ellipsoid2},
119 L{Datum} or L{a_f2Tuple}) or C{scalar} ellipsoid's
120 equatorial radius (C{meter}).
121 @kwarg f: C{None} or the ellipsoid flattening (C{scalar}), required
122 for C{scalar} B{C{a_ellipsoid}}, C{B{f}=0} represents a
123 sphere, negative B{C{f}} a prolate ellipsoid.
124 @kwarg lon00: An arbitrary, I{"polar"} longitude (C{degrees}), see the
125 C{reverse} method.
126 @kwarg name: Optional C{B{name}=NN} (C{str}).
128 @raise EcefError: If B{C{a_ellipsoid}} not L{Ellipsoid}, L{Ellipsoid2},
129 L{Datum} or L{a_f2Tuple} or C{scalar} or B{C{f}} not
130 C{scalar} or if C{scalar} B{C{a_ellipsoid}} not positive
131 or B{C{f}} not less than 1.0.
132 '''
133 try:
134 E = a_ellipsoid
135 if f is None:
136 pass
137 elif _isRadius(E) and isscalar(f):
138 E = a_f2Tuple(E, f)
139 else:
140 raise ValueError() # _invalid_
142 if not _isin(E, _EWGS84, _WGS84):
143 d = _ellipsoidal_datum(E, **name)
144 E = d.ellipsoid
145 if E.a < EPS or E.f > EPS1:
146 raise ValueError() # _invalid_
147 self._datum = d
148 self._E = E
150 except (TypeError, ValueError) as x:
151 t = unstr(self.classname, a=a_ellipsoid, f=f)
152 raise EcefError(_SPACE_(t, _ellipsoid_), cause=x)
154 if name:
155 self.name = name
156 if lon00 is not INT0:
157 self.lon00 = lon00
159 def __eq__(self, other):
160 '''Compare this and an other Ecef.
162 @arg other: The other ecef (C{Ecef*}).
164 @return: C{True} if equal, C{False} otherwise.
165 '''
166 return other is self or (isinstance(other, self.__class__) and
167 other.ellipsoid == self.ellipsoid)
169 @Property_RO
170 def datum(self):
171 '''Get the datum (L{Datum}).
172 '''
173 return self._datum
175 @Property_RO
176 def ellipsoid(self):
177 '''Get the ellipsoid (L{Ellipsoid} or L{Ellipsoid2}).
178 '''
179 return self._E
181 @Property_RO
182 def equatoradius(self):
183 '''Get the C{ellipsoid}'s equatorial radius, semi-axis (C{meter}).
184 '''
185 return self.ellipsoid.a
187 a = equatorialRadius = equatoradius # Karney property
189 @Property_RO
190 def flattening(self): # Karney property
191 '''Get the C{ellipsoid}'s flattening (C{scalar}), positive for
192 I{oblate}, negative for I{prolate} or C{0} for I{near-spherical}.
193 '''
194 return self.ellipsoid.f
196 f = flattening
198 def _forward(self, lat, lon, h, name, M=False, _philam=False): # in .ltp.LocalCartesian.forward and -.reset
199 '''(INTERNAL) Common for all C{Ecef*}.
200 '''
201 if _philam: # lat, lon in radians
202 sa, ca, sb, cb = sincos2_(lat, lon)
203 lat = Lat(degrees90( lat), Error=EcefError)
204 lon = Lon(degrees180(lon), Error=EcefError)
205 else:
206 sa, ca, sb, cb = sincos2d_(lat, lon)
208 E = self.ellipsoid
209 n = E.roc1_(sa, ca) if self._isYou else E.roc1_(sa)
210 z = (h + n * E.e21) * sa
211 x = (h + n) * ca
213 m = self._Matrix(sa, ca, sb, cb) if M else None
214 return Ecef9Tuple(x * cb, x * sb, z, lat, lon, h,
215 0, m, self.datum,
216 name=self._name__(name))
218 def forward(self, latlonh, lon=None, height=0, M=False, **name):
219 '''Convert from geodetic C{(lat, lon, height)} to geocentric C{(x, y, z)}.
221 @arg latlonh: Either a C{LatLon}, an L{Ecef9Tuple} or C{scalar}
222 latitude (C{degrees}).
223 @kwarg lon: Optional C{scalar} longitude for C{scalar} B{C{latlonh}}
224 (C{degrees}).
225 @kwarg height: Optional height (C{meter}), vertically above (or below)
226 the surface of the ellipsoid.
227 @kwarg M: Optionally, return the rotation L{EcefMatrix} (C{bool}).
228 @kwarg name: Optional C{B{name}=NN} (C{str}).
230 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
231 geocentric C{(x, y, z)} coordinates for the given geodetic ones
232 C{(lat, lon, height)}, case C{C} 0, optional C{M} (L{EcefMatrix})
233 and C{datum} if available.
235 @raise EcefError: If B{C{latlonh}} not C{LatLon}, L{Ecef9Tuple} or
236 C{scalar} or B{C{lon}} not C{scalar} for C{scalar}
237 B{C{latlonh}} or C{abs(lat)} exceeds 90°.
239 @note: Use method C{.forward_} to specify C{lat} and C{lon} in C{radians}
240 and avoid double angle conversions.
241 '''
242 llhn = _llhn4(latlonh, lon, height, **name)
243 return self._forward(*llhn, M=M)
245 def forward_(self, phi, lam, height=0, M=False, **name):
246 '''Like method C{.forward} except with geodetic lat- and longitude given
247 in I{radians}.
249 @arg phi: Latitude in I{radians} (C{scalar}).
250 @arg lam: Longitude in I{radians} (C{scalar}).
251 @kwarg height: Optional height (C{meter}), vertically above (or below)
252 the surface of the ellipsoid.
253 @kwarg M: Optionally, return the rotation L{EcefMatrix} (C{bool}).
254 @kwarg name: Optional C{B{name}=NN} (C{str}).
256 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)}
257 with C{lat} set to C{degrees90(B{phi})} and C{lon} to
258 C{degrees180(B{lam})}.
260 @raise EcefError: If B{C{phi}} or B{C{lam}} invalid or not C{scalar}.
261 '''
262 try: # like function C{_llhn4} below
263 plhn = Phi(phi), Lam(lam), Height(height), _name__(name)
264 except (TypeError, ValueError) as x:
265 raise EcefError(phi=phi, lam=lam, height=height, cause=x)
266 return self._forward(*plhn, M=M, _philam=True)
268 @property_ROver
269 def _Geocentrics(self):
270 '''(INTERNAL) Get the valid geocentric classes. I{once}.
271 '''
272 return (Ecef9Tuple, # overwrite property_ROver
273 _MODS.vector3d.Vector3d) # _MODS.cartesianBase.CartesianBase
275 @Property_RO
276 def _isYou(self):
277 '''(INTERNAL) Is this an C{EcefYou}?.
278 '''
279 return isinstance(self, EcefYou)
281 @property
282 def lon00(self):
283 '''Get the I{"polar"} longitude (C{degrees}), see method C{reverse}.
284 '''
285 return self._lon00
287 @lon00.setter # PYCHOK setter!
288 def lon00(self, lon00):
289 '''Set the I{"polar"} longitude (C{degrees}), see method C{reverse}.
290 '''
291 self._lon00 = Degrees(lon00=lon00)
293 def _Matrix(self, sa, ca, sb, cb):
294 '''Creation a rotation matrix.
296 @arg sa: C{sin(phi)} (C{float}).
297 @arg ca: C{cos(phi)} (C{float}).
298 @arg sb: C{sin(lambda)} (C{float}).
299 @arg cb: C{cos(lambda)} (C{float}).
301 @return: An L{EcefMatrix}.
302 '''
303 return self._xnamed(EcefMatrix(sa, ca, sb, cb))
305 def _polon(self, y, x, R, **lon00_name):
306 '''(INTERNAL) Handle I{"polar"} longitude.
307 '''
308 return atan2d(y, x) if R else _xkwds_get(lon00_name, lon00=self.lon00)
310 def reverse(self, xyz, y=None, z=None, M=False, **lon00_name): # PYCHOK no cover
311 '''I{Must be overloaded}.'''
312 self._notOverloaded(xyz, y=y, z=z, M=M, **lon00_name)
314 def toStr(self, prec=9, **unused): # PYCHOK signature
315 '''Return this C{Ecef*} as a string.
317 @kwarg prec: Precision, number of decimal digits (0..9).
319 @return: This C{Ecef*} (C{str}).
320 '''
321 return self.attrs(_a_, _f_, _datum_, _name_, prec=prec) # _ellipsoid_
324class EcefFarrell21(_EcefBase):
325 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF)
326 coordinates based on I{Jay A. Farrell}'s U{Table 2.1<https://Books.Google.com/
327 books?id=fW4foWASY6wC>}, page 29.
328 '''
330 def reverse(self, xyz, y=None, z=None, M=None, **lon00_name): # PYCHOK unused M
331 '''Convert from geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)} using
332 I{Farrell}'s U{Table 2.1<https://Books.Google.com/books?id=fW4foWASY6wC>},
333 page 29, aka the I{Heikkinen application} of U{Ferrari's solution
334 <https://WikiPedia.org/wiki/Geographic_coordinate_conversion>}.
336 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x}
337 coordinate (C{meter}).
338 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}).
339 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}).
340 @kwarg M: I{Ignored}, rotation matrix C{M} not available.
341 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument
342 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude
343 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}.
345 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
346 geodetic coordinates C{(lat, lon, height)} for the given geocentric
347 ones C{(x, y, z)}, case C{C=1}, C{M=None} always and C{datum}
348 if available.
350 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or B{C{z}}
351 not C{scalar} for C{scalar} B{C{xyz}} or C{sqrt} domain or
352 zero division error.
354 @see: L{EcefFarrell22} and L{EcefVeness}.
355 '''
356 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name)
358 E = self.ellipsoid
359 a = E.a
360 a2 = E.a2
361 b2 = E.b2
362 e2 = E.e2
363 e2_ = E.e2abs * E.a2_b2 # (E.e * E.a_b)**2 = 0.0820944... WGS84
364 e4 = E.e4
366 try: # names as page 29
367 z2 = z**2
368 ez = z2 * (_1_0 - e2) # E.e2s2(z)
370 p = hypot(x, y)
371 p2 = p**2
372 G = p2 + ez - e2 * (a2 - b2) # p2 + ez - e4 * a2
373 F = b2 * z2 * 54
374 c = e4 * p2 * F / G**3
375 s = cbrt(sqrt(c * (c + _2_0)) + c + _1_0)
376 G *= fsumf_(s , _1_0, _1_0 / s) # k
377 P = F / (G**2 * _3_0)
378 Q = sqrt(_2_0 * e4 * P + _1_0)
379 Q1 = Q + _1_0
380 r0 = P * p * e2 / Q1 - sqrt(fsumf_(a2 * (Q1 / Q) * _0_5,
381 -P * ez / (Q * Q1),
382 -P * p2 * _0_5))
383 r = p + e2 * r0
384 v = b2 / (sqrt(r**2 + ez) * a) # z0 / z
386 h = hypot(r, z) * (_1_0 - v)
387 lat = atan1d((e2_ * v + _1_0) * z, p)
388 lon = self._polon(y, x, p, **lon00_name)
389 # note, phi and lam are swapped on page 29
391 except (ValueError, ZeroDivisionError) as X:
392 raise EcefError(x=x, y=y, z=z, cause=X)
394 return Ecef9Tuple(x, y, z, lat, lon, h,
395 1, None, self.datum,
396 name=self._name__(name))
399class EcefFarrell22(_EcefBase):
400 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF)
401 coordinates based on I{Jay A. Farrell}'s U{Table 2.2<https://Books.Google.com/
402 books?id=fW4foWASY6wC>}, page 30.
403 '''
405 def reverse(self, xyz, y=None, z=None, M=None, **lon00_name): # PYCHOK unused M
406 '''Convert from geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)} using
407 I{Farrell}'s U{Table 2.2<https://Books.Google.com/books?id=fW4foWASY6wC>},
408 page 30.
410 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x}
411 coordinate (C{meter}).
412 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}).
413 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}).
414 @kwarg M: I{Ignored}, rotation matrix C{M} not available.
415 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument
416 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude
417 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}.
419 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
420 geodetic coordinates C{(lat, lon, height)} for the given geocentric
421 ones C{(x, y, z)}, case C{C=1}, C{M=None} always and C{datum}
422 if available.
424 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or B{C{z}}
425 not C{scalar} for C{scalar} B{C{xyz}} or C{sqrt} domain or
426 zero division error.
428 @see: L{EcefFarrell21} and L{EcefVeness}.
429 '''
430 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name)
432 E = self.ellipsoid
433 a = E.a
434 b = E.b
436 try: # see EcefVeness.reverse
437 p = hypot(x, y)
438 lon = self._polon(y, x, p, **lon00_name)
440 s, c = sincos2(atan2(z * a, p * b)) # == _norm3
441 lat = atan1d(z + s**3 * b * E.e22,
442 p - c**3 * a * E.e2)
444 s, c = sincos2d(lat)
445 if c: # E.roc1_(s) = E.a / sqrt(1 - E.e2 * s**2)
446 h = p / c - (E.roc1_(s) if s else a)
447 else: # polar
448 h = fabs(z) - b
449 # note, phi and lam are swapped on page 30
451 except (ValueError, ZeroDivisionError) as e:
452 raise EcefError(x=x, y=y, z=z, cause=e)
454 return Ecef9Tuple(x, y, z, lat, lon, h,
455 1, None, self.datum,
456 name=self._name__(name))
459class EcefKarney(_EcefBase):
460 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF)
461 coordinates transcoded from I{Karney}'s C++ U{Geocentric<https://GeographicLib.SourceForge.io/
462 C++/doc/classGeographicLib_1_1Geocentric.html>} methods.
464 @note: On methods C{.forward} and C{.forwar_}, let C{v} be a unit vector located
465 at C{(lat, lon, h)}. We can express C{v} as column vectors in one of two
466 ways, C{v1} in East, North, Up (ENU) coordinates (where the components are
467 relative to a local coordinate system at C{C(lat0, lon0, h0)}) or as C{v0}
468 in geocentric C{x, y, z} coordinates. Then, M{v0 = M ⋅ v1} where C{M} is
469 the rotation matrix.
470 '''
472 @Property_RO
473 def hmax(self):
474 '''Get the distance or height limit (C{meter}, conventionally).
475 '''
476 return self.equatoradius / EPS_2 # self.equatoradius * _2_EPS, 12M lighyears
478 def reverse(self, xyz, y=None, z=None, M=False, **lon00_name):
479 '''Convert from geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)}.
481 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x}
482 coordinate (C{meter}).
483 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}).
484 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}).
485 @kwarg M: Optionally, return the rotation L{EcefMatrix} (C{bool}).
486 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument
487 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude
488 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}.
490 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
491 geodetic coordinates C{(lat, lon, height)} for the given geocentric
492 ones C{(x, y, z)}, case C{C}, optional C{M} (L{EcefMatrix}) and
493 C{datum} if available.
495 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or B{C{z}}
496 not C{scalar} for C{scalar} B{C{xyz}}.
498 @note: In general, there are multiple solutions and the result which minimizes
499 C{height} is returned, i.e., the C{(lat, lon)} corresponding to the
500 closest point on the ellipsoid. If there are still multiple solutions
501 with different latitudes (applies only if C{z} = 0), then the solution
502 with C{lat} > 0 is returned. If there are still multiple solutions with
503 different longitudes (applies only if C{x} = C{y} = 0), then C{lon00} is
504 returned. The returned C{lon} is in the range [−180°, 180°] and C{height}
505 is not below M{−E.a * (1 − E.e2) / sqrt(1 − E.e2 * sin(lat)**2)}. Like
506 C{forward} above, M{v1 = Transpose(M) ⋅ v0}.
507 '''
508 def _norm3(y, x):
509 h = hypot(y, x) # EPS0, EPS_2
510 return (y / h, x / h, h) if h > 0 else (_0_0, _1_0, h)
512 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name)
514 E = self.ellipsoid
515 f = E.f
517 sb, cb, R = _norm3(y, x)
518 h = hypot(R, z) # distance to earth center
519 if h > self.hmax: # PYCHOK no cover
520 # We are really far away (> 12M light years). Treat the earth
521 # as a point and h above as an acceptable approximation to the
522 # height. This avoids overflow, e.g., in the computation of d
523 # below. It's possible that h has overflowed to INF, that's OK.
524 # Treat finite x, y, but R overflows to +INF by scaling by 2.
525 sb, cb, R = _norm3(y * _0_5, x * _0_5)
526 sa, ca, _ = _norm3(z * _0_5, R)
527 C = 1
529 elif E.e4: # E.isEllipsoidal
530 # Treat prolate spheroids by swapping R and Z here and by
531 # switching the arguments to phi = atan2(...) at the end.
532 p = (R / E.a)**2
533 q = (z / E.a)**2 * E.e21
534 if f < 0:
535 p, q = q, p
536 r = fsumf_(p, q, -E.e4)
537 e = E.e4 * q
538 if e or r > 0:
539 # Avoid possible division by zero when r = 0 by multiplying
540 # equations for s and t by r^3 and r, respectively.
541 s = d = e * p / _4_0 # s = r^3 * s
542 u = r = r / _6_0
543 r2 = r**2
544 r3 = r2 * r
545 t3 = r3 + s
546 d *= t3 + r3
547 if d < 0:
548 # t is complex, but the way u is defined, the result is real.
549 # There are three possible cube roots. We choose the root
550 # which avoids cancellation. Note, d < 0 implies r < 0.
551 u += cos(atan2(sqrt(-d), -t3) / _3_0) * r * _2_0
552 else:
553 # Pick the sign on the sqrt to maximize abs(t3). This
554 # minimizes loss of precision due to cancellation. The
555 # result is unchanged because of the way the t is used
556 # in definition of u.
557 if d > 0:
558 t3 += copysign0(sqrt(d), t3) # t3 = (r * t)^3
559 # N.B. cbrt always returns the real root, cbrt(-8) = -2.
560 t = cbrt(t3) # t = r * t
561 if t: # t can be zero; but then r2 / t -> 0.
562 u = fsumf_(u, t, r2 / t)
563 v = sqrt(e + u**2) # guaranteed positive
564 # Avoid loss of accuracy when u < 0. Underflow doesn't occur in
565 # E.e4 * q / (v - u) because u ~ e^4 when q is small and u < 0.
566 u = (e / (v - u)) if u < 0 else (u + v) # u+v, guaranteed positive
567 # Need to guard against w going negative due to roundoff in u - q.
568 w = E.e2abs * (u - q) / (_2_0 * v)
569 # Rearrange expression for k to avoid loss of accuracy due to
570 # subtraction. Division by 0 not possible because u > 0, w >= 0.
571 k1 = k2 = (u / (sqrt(u + w**2) + w)) if w > 0 else sqrt(u)
572 if f < 0:
573 k1 -= E.e2
574 else:
575 k2 += E.e2
576 sa, ca, h = _norm3(z / k1, R / k2)
577 h *= k1 - E.e21
578 C = 2
580 else: # e = E.e4 * q == 0 and r <= 0
581 # This leads to k = 0 (oblate, equatorial plane) and k + E.e^2 = 0
582 # (prolate, rotation axis) and the generation of 0/0 in the general
583 # formulas for phi and h, using the general formula and division
584 # by 0 in formula for h. Handle this case by taking the limits:
585 # f > 0: z -> 0, k -> E.e2 * sqrt(q) / sqrt(E.e4 - p)
586 # f < 0: r -> 0, k + E.e2 -> -E.e2 * sqrt(q) / sqrt(E.e4 - p)
587 q = E.e4 - p
588 if f < 0:
589 p, q = q, p
590 e = E.a
591 else:
592 e = E.b2_a
593 sa, ca, h = _norm3(sqrt(q * E._1_e21), sqrt(p))
594 if z < 0: # for tiny negative z, not for prolate
595 sa = neg(sa)
596 h *= neg(e / E.e2abs)
597 C = 3
599 else: # E.e4 == 0, spherical case
600 # Dealing with underflow in the general case with E.e2 = 0 is
601 # difficult. Origin maps to North pole, same as with ellipsoid.
602 sa, ca, _ = _norm3((z if h else _1_0), R)
603 h -= E.a
604 C = 4
606 # lon00 <https://GitHub.com/mrJean1/PyGeodesy/issues/77>
607 lon = self._polon(sb, cb, R, **lon00_name)
608 m = self._Matrix(sa, ca, sb, cb) if M else None
609 return Ecef9Tuple(x, y, z, atan1d(sa, ca), lon, h,
610 C, m, self.datum, name=self._name__(name))
613class EcefSudano(_EcefBase):
614 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF) coordinates
615 based on I{John J. Sudano}'s U{paper<https://www.ResearchGate.net/publication/3709199>}.
616 '''
617 _tol = EPS2
619 def reverse(self, xyz, y=None, z=None, M=None, **lon00_name): # PYCHOK unused M
620 '''Convert from geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)} using
621 I{Sudano}'s U{iterative method<https://www.ResearchGate.net/publication/3709199>}.
623 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x}
624 coordinate (C{meter}).
625 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}).
626 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}).
627 @kwarg M: I{Ignored}, rotation matrix C{M} not available.
628 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument
629 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude
630 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}.
632 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with geodetic
633 coordinates C{(lat, lon, height)} for the given geocentric ones C{(x, y, z)},
634 iteration C{C}, C{M=None} always and C{datum} if available.
636 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or B{C{z}}
637 not C{scalar} for C{scalar} B{C{xyz}} or no convergence.
638 '''
639 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name)
641 E = self.ellipsoid
642 e = E.e2 * E.a
643 R = hypot(x, y) # Rh
644 d = e - R
646 lat = atan1d(z, R * E.e21)
647 sa, ca = sincos2d(fabs(lat))
648 # Sudano's Eq (A-6) and (A-7) refactored/reduced,
649 # replacing Rn from Eq (A-4) with n = E.a / ca:
650 # N = ca**2 * ((z + E.e2 * n * sa) * ca - R * sa)
651 # = ca**2 * (z * ca + E.e2 * E.a * sa - R * sa)
652 # = ca**2 * (z * ca + (E.e2 * E.a - R) * sa)
653 # D = ca**3 * (E.e2 * n / E.e2s2(sa)) - R
654 # = ca**2 * (E.e2 * E.a / E.e2s2(sa) - R / ca**2)
655 # N / D = (z * ca + (E.e2 * E.a - R) * sa) /
656 # (E.e2 * E.a / E.e2s2(sa) - R / ca**2)
657 tol = self.tolerance
658 _S2 = Fsum(sa).fsum2f_
659 for i in range(1, _TRIPS):
660 ca2 = _1_0 - sa**2
661 if ca2 < EPS_2: # PYCHOK no cover
662 ca = _0_0
663 break
664 ca = sqrt(ca2)
665 r = e / E.e2s2(sa) - R / ca2
666 if fabs(r) < EPS_2:
667 break
668 lat = None
669 sa, t = _S2(-z * ca / r, -d * sa / r)
670 if fabs(t) < tol:
671 break
672 else:
673 t = unstr(self.reverse, x=x, y=y, z=z)
674 raise EcefError(t, txt=Fmt.no_convergence(r, tol))
676 if lat is None:
677 lat = copysign0(atan1d(fabs(sa), ca), z)
678 lon = self._polon(y, x, R, **lon00_name)
680 h = fsumf_(R * ca, fabs(z * sa), -E.a * E.e2s(sa)) # use Veness'
681 # because Sudano's Eq (7) doesn't produce the correct height
682 # h = (fabs(z) + R - E.a * cos(a + E.e21) * sa / ca) / (ca + sa)
683 return Ecef9Tuple(x, y, z, lat, lon, h,
684 i, None, self.datum, # C=i, M=None
685 iteration=i, name=self._name__(name))
687 @property_doc_(''' the convergence tolerance (C{float}).''')
688 def tolerance(self):
689 '''Get the convergence tolerance (C{scalar}).
690 '''
691 return self._tol
693 @tolerance.setter # PYCHOK setter!
694 def tolerance(self, tol):
695 '''Set the convergence tolerance (C{scalar}).
697 @raise EcefError: Non-scalar or invalid B{C{tol}}.
698 '''
699 self._tol = Scalar_(tolerance=tol, low=EPS, Error=EcefError)
702class EcefVeness(_EcefBase):
703 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF) coordinates
704 transcoded from I{Chris Veness}' JavaScript classes U{LatLonEllipsoidal, Cartesian<https://
705 www.Movable-Type.co.UK/scripts/geodesy/docs/latlon-ellipsoidal.js.html>}.
707 @see: U{I{A Guide to Coordinate Systems in Great Britain}<https://www.OrdnanceSurvey.co.UK/
708 documents/resources/guide-coordinate-systems-great-britain.pdf>}, section I{B) Converting
709 between 3D Cartesian and ellipsoidal latitude, longitude and height coordinates}.
710 '''
712 def reverse(self, xyz, y=None, z=None, M=None, **lon00_name): # PYCHOK unused M
713 '''Conversion from geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)}
714 transcoded from I{Chris Veness}' U{JavaScript<https://www.Movable-Type.co.UK/
715 scripts/geodesy/docs/latlon-ellipsoidal.js.html>}.
717 Uses B. R. Bowring’s formulation for μm precision in concise form U{I{The accuracy
718 of geodetic latitude and height equations}<https://www.ResearchGate.net/publication/
719 233668213>}, Survey Review, Vol 28, 218, Oct 1985.
721 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x}
722 coordinate (C{meter}).
723 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}).
724 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}).
725 @kwarg M: I{Ignored}, rotation matrix C{M} not available.
726 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument
727 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude
728 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}.
730 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
731 geodetic coordinates C{(lat, lon, height)} for the given geocentric
732 ones C{(x, y, z)}, case C{C}, C{M=None} always and C{datum} if available.
734 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or B{C{z}}
735 not C{scalar} for C{scalar} B{C{xyz}}.
737 @see: Toms, Ralph M. U{I{An Efficient Algorithm for Geocentric to Geodetic
738 Coordinate Conversion}<https://www.OSTI.gov/scitech/biblio/110235>},
739 Sept 1995 and U{I{An Improved Algorithm for Geocentric to Geodetic
740 Coordinate Conversion}<https://www.OSTI.gov/scitech/servlets/purl/231228>},
741 Apr 1996, both from Lawrence Livermore National Laboratory (LLNL) and
742 Sudano, John J, U{I{An exact conversion from an Earth-centered coordinate
743 system to latitude longitude and altitude}<https://www.ResearchGate.net/
744 publication/3709199>}.
745 '''
746 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name)
748 E = self.ellipsoid
749 a = E.a
751 p = hypot(x, y) # distance from minor axis
752 r = hypot(p, z) # polar radius
753 if min(p, r) > EPS0:
754 b = E.b * E.e22
755 # parametric latitude (Bowring eqn 17, replaced)
756 t = (E.b * z) / (a * p) * (_1_0 + b / r)
757 c = _1_0 / hypot1(t)
758 s = c * t
759 # geodetic latitude (Bowring eqn 18)
760 lat = atan1d(z + s**3 * b,
761 p - c**3 * a * E.e2)
763 # height above ellipsoid (Bowring eqn 7)
764 sa, ca = sincos2d(lat)
765# r = a / E.e2s(sa) # length of normal terminated by minor axis
766# h = p * ca + z * sa - (a * a / r)
767 h = fsumf_(p * ca, z * sa, -a * E.e2s(sa))
768 C = 1
770 # see <https://GIS.StackExchange.com/questions/28446>
771 elif p > EPS: # lat arbitrarily zero, equatorial lon
772 C, lat, h = 2, _0_0, (p - a)
774 else: # polar lat, lon arbitrarily lon00
775 C, lat, h = 3, (_N_90_0 if z < 0 else _90_0), (fabs(z) - E.b)
777 lon = self._polon(y, x, p, **lon00_name)
778 return Ecef9Tuple(x, y, z, lat, lon, h,
779 C, None, self.datum, # M=None
780 name=self._name__(name))
783class EcefYou(_EcefBase):
784 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF) coordinates
785 using I{Rey-Jer You}'s U{transformation<https://www.ResearchGate.net/publication/240359424>}
786 for I{non-prolate} ellipsoids.
788 @see: Featherstone, W.E., Claessens, S.J. U{I{Closed-form transformation between geodetic and
789 ellipsoidal coordinates}<https://Espace.Curtin.edu.AU/bitstream/handle/20.500.11937/
790 11589/115114_9021_geod2ellip_final.pdf>} Studia Geophysica et Geodaetica, 2008, 52,
791 pages 1-18 and U{PyMap3D <https://PyPI.org/project/pymap3d>}.
792 '''
794 def __init__(self, a_ellipsoid=_EWGS84, f=None, **lon00_name): # PYCHOK signature
795 _EcefBase.__init__(self, a_ellipsoid, f=f, **lon00_name) # inherited documentation
796 self._ee2 = EcefYou._ee2(self.ellipsoid)
798 @staticmethod
799 def _ee2(E):
800 e2 = E.a2 - E.b2
801 if e2 < 0 or E.f < 0:
802 raise EcefError(ellipsoid=E, txt=_prolate_)
803 return sqrt0(e2), e2
805 def reverse(self, xyz, y=None, z=None, M=None, **lon00_name): # PYCHOK unused M
806 '''Convert geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)}
807 using I{Rey-Jer You}'s transformation.
809 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x}
810 coordinate (C{meter}).
811 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}).
812 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}).
813 @kwarg M: I{Ignored}, rotation matrix C{M} not available.
814 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument
815 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude
816 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}.
818 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with
819 geodetic coordinates C{(lat, lon, height)} for the given geocentric
820 ones C{(x, y, z)}, case C{C=1}, C{M=None} always and C{datum} if
821 available.
823 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or
824 B{C{z}} not C{scalar} for C{scalar} B{C{xyz}} or the
825 ellipsoid is I{prolate}.
826 '''
827 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name)
829 E = self.ellipsoid
830 e, e2 = self._ee2
832 q = hypot(x, y) # R
833 u = Fpowers(2, x, y, z) - e2
834 u = u.fadd_(hypot(u, e * z * _2_0)).fover(_2_0)
835 if u > EPS02:
836 u = sqrt(u)
837 p = hypot(u, e)
838 B = atan1(p * z, u * q) # beta0 = atan(p / u * z / q)
839 sB, cB = sincos2(B)
840 if cB and sB:
841 p *= E.a
842 d = (p / cB - e2 * cB) / sB
843 if isnon0(d):
844 B += fsumf_(u * E.b, -p, e2) / d
845 sB, cB = sincos2(B)
846 elif u < (-EPS2):
847 raise EcefError(x=x, y=y, z=z, u=u, txt=_singular_)
848 else:
849 sB, cB = _copysign_1_0(z), _0_0
851 lat = atan1d(E.a * sB, E.b * cB) # atan(E.a_b * tan(B))
852 lon = self._polon(y, x, q, **lon00_name)
854 h = hypot(z - E.b * sB, q - E.a * cB)
855 if hypot2_(x, y, z * E.a_b) < E.a2:
856 h = neg(h) # inside ellipsoid
857 return Ecef9Tuple(x, y, z, lat, lon, h,
858 1, None, self.datum, # C=1, M=None
859 name=self._name__(name))
862class EcefMatrix(_NamedTuple):
863 '''A rotation matrix known as I{East-North-Up (ENU) to ECEF}.
865 @see: U{From ENU to ECEF<https://WikiPedia.org/wiki/
866 Geographic_coordinate_conversion#From_ECEF_to_ENU>} and
867 U{Issue #74<https://Github.com/mrJean1/PyGeodesy/issues/74>}.
868 '''
869 _Names_ = ('_0_0_', '_0_1_', '_0_2_', # row-order
870 '_1_0_', '_1_1_', '_1_2_',
871 '_2_0_', '_2_1_', '_2_2_')
872 _Units_ = (Scalar,) * len(_Names_)
874 def _validate(self, **unused): # PYCHOK unused
875 '''(INTERNAL) Allow C{_Names_} with leading underscore.
876 '''
877 _NamedTuple._validate(self, underOK=True)
879 def __new__(cls, sa, ca, sb, cb, *_more):
880 '''New L{EcefMatrix} matrix.
882 @arg sa: C{sin(phi)} (C{float}).
883 @arg ca: C{cos(phi)} (C{float}).
884 @arg sb: C{sin(lambda)} (C{float}).
885 @arg cb: C{cos(lambda)} (C{float}).
886 @arg _more: (INTERNAL) from C{.multiply}.
888 @raise EcefError: If B{C{sa}}, B{C{ca}}, B{C{sb}} or
889 B{C{cb}} outside M{[-1.0, +1.0]}.
890 '''
891 t = sa, ca, sb, cb
892 if _more: # all 9 matrix elements ...
893 t += _more # ... from .multiply
895 elif max(map(fabs, t)) > _1_0:
896 raise EcefError(unstr(EcefMatrix, *t))
898 else: # build matrix from the following quaternion operations
899 # qrot(lam, [0,0,1]) * qrot(phi, [0,-1,0]) * [1,1,1,1]/2
900 # or
901 # qrot(pi/2 + lam, [0,0,1]) * qrot(-pi/2 + phi, [-1,0,0])
902 # where
903 # qrot(t,v) = [cos(t/2), sin(t/2)*v[1], sin(t/2)*v[2], sin(t/2)*v[3]]
905 # Local X axis (East) in geocentric coords
906 # M[0] = -slam; M[3] = clam; M[6] = 0;
907 # Local Y axis (North) in geocentric coords
908 # M[1] = -clam * sphi; M[4] = -slam * sphi; M[7] = cphi;
909 # Local Z axis (Up) in geocentric coords
910 # M[2] = clam * cphi; M[5] = slam * cphi; M[8] = sphi;
911 t = (-sb, -cb * sa, cb * ca,
912 cb, -sb * sa, sb * ca,
913 _0_0, ca, sa)
915 return _NamedTuple.__new__(cls, *t)
917 def column(self, column):
918 '''Get this matrix' B{C{column}} 0, 1 or 2 as C{3-tuple}.
919 '''
920 if 0 <= column < 3:
921 return self[column::3]
922 raise _IndexError(column=column)
924 def copy(self, **unused): # PYCHOK signature
925 '''Make a shallow or deep copy of this instance.
927 @return: The copy (C{This class} or subclass thereof).
928 '''
929 return self.classof(*self)
931 __copy__ = __deepcopy__ = copy
933 @Property_RO
934 def matrix3(self):
935 '''Get this matrix' rows (C{3-tuple} of 3 C{3-tuple}s).
936 '''
937 return tuple(map(self.row, range(3)))
939 @Property_RO
940 def matrixTransposed3(self):
941 '''Get this matrix' I{Transposed} rows (C{3-tuple} of 3 C{3-tuple}s).
942 '''
943 return tuple(map(self.column, range(3)))
945 def multiply(self, other):
946 '''Matrix multiply M{M0' ⋅ M} this matrix I{Transposed}
947 with an other matrix.
949 @arg other: The other matrix (L{EcefMatrix}).
951 @return: The matrix product (L{EcefMatrix}).
953 @raise TypeError: If B{C{other}} is not an L{EcefMatrix}.
954 '''
955 _xinstanceof(EcefMatrix, other=other)
956 # like LocalCartesian.MatrixMultiply, C{self.matrixTransposed3 X other.matrix3}
957 # <https://GeographicLib.SourceForge.io/C++/doc/LocalCartesian_8cpp_source.html>
958 # X = (fdot(self.column(r), *other.column(c)) for r in (0,1,2) for c in (0,1,2))
959 X = (fdot(self[r::3], *other[c::3]) for r in range(3) for c in range(3))
960 return _xnamed(EcefMatrix(*X), typename(EcefMatrix.multiply))
962 def rotate(self, xyz, *xyz0):
963 '''Forward rotation M{M0' ⋅ ([x, y, z] - [x0, y0, z0])'}.
965 @arg xyz: Local C{(x, y, z)} coordinates (C{3-tuple}).
966 @arg xyz0: Optional, local C{(x0, y0, z0)} origin (C{3-tuple}).
968 @return: Rotated C{(x, y, z)} location (C{3-tuple}).
970 @raise LenError: Unequal C{len(B{xyz})} and C{len(B{xyz0})}.
971 '''
972 if xyz0:
973 if len(xyz0) != len(xyz):
974 raise LenError(self.rotate, xyz0=len(xyz0), xyz=len(xyz))
975 xyz = tuple(c - c0 for c, c0 in zip(xyz, xyz0))
977 # x' = M[0] * x + M[3] * y + M[6] * z
978 # y' = M[1] * x + M[4] * y + M[7] * z
979 # z' = M[2] * x + M[5] * y + M[8] * z
980 return (fdot(xyz, *self[0::3]), # .column(0)
981 fdot(xyz, *self[1::3]), # .column(1)
982 fdot(xyz, *self[2::3])) # .column(2)
984 def row(self, row):
985 '''Get this matrix' B{C{row}} 0, 1 or 2 as C{3-tuple}.
986 '''
987 if 0 <= row < 3:
988 r = row * 3
989 return self[r:r+3]
990 raise _IndexError(row=row)
992 def unrotate(self, xyz, *xyz0):
993 '''Inverse rotation M{[x0, y0, z0] + M0 ⋅ [x,y,z]'}.
995 @arg xyz: Local C{(x, y, z)} coordinates (C{3-tuple}).
996 @arg xyz0: Optional, local C{(x0, y0, z0)} origin (C{3-tuple}).
998 @return: Unrotated C{(x, y, z)} location (C{3-tuple}).
1000 @raise LenError: Unequal C{len(B{xyz})} and C{len(B{xyz0})}.
1001 '''
1002 if xyz0:
1003 if len(xyz0) != len(xyz):
1004 raise LenError(self.unrotate, xyz0=len(xyz0), xyz=len(xyz))
1005 _xyz = _1_0_1T + xyz
1006 # x' = x0 + M[0] * x + M[1] * y + M[2] * z
1007 # y' = y0 + M[3] * x + M[4] * y + M[5] * z
1008 # z' = z0 + M[6] * x + M[7] * y + M[8] * z
1009 xyz_ = (fdot(_xyz, xyz0[0], *self[0:3]), # .row(0)
1010 fdot(_xyz, xyz0[1], *self[3:6]), # .row(1)
1011 fdot(_xyz, xyz0[2], *self[6:9])) # .row(2)
1012 else:
1013 # x' = M[0] * x + M[1] * y + M[2] * z
1014 # y' = M[3] * x + M[4] * y + M[5] * z
1015 # z' = M[6] * x + M[7] * y + M[8] * z
1016 xyz_ = (fdot(xyz, *self[0:3]), # .row(0)
1017 fdot(xyz, *self[3:6]), # .row(1)
1018 fdot(xyz, *self[6:9])) # .row(2)
1019 return xyz_
1022class Ecef9Tuple(_NamedTuple, _NamedLocal):
1023 '''9-Tuple C{(x, y, z, lat, lon, height, C, M, datum)} with I{geocentric} C{x},
1024 C{y} and C{z} plus I{geodetic} C{lat}, C{lon} and C{height}, case C{C} (see
1025 the C{Ecef*.reverse} methods) and optionally, rotation matrix C{M} (L{EcefMatrix})
1026 and C{datum}, with C{lat} and C{lon} in C{degrees} and C{x}, C{y}, C{z} and
1027 C{height} in C{meter}, conventionally.
1028 '''
1029 _Names_ = (_x_, _y_, _z_, _lat_, _lon_, _height_, _C_, _M_, _datum_)
1030 _Units_ = ( Meter, Meter, Meter, Lat, Lon, Height, Int, _Pass, _Pass)
1032 @property_ROver
1033 def _CartesianBase(self):
1034 '''(INTERNAL) Get class C{CartesianBase}, I{once}.
1035 '''
1036 return _MODS.cartesianBase.CartesianBase # overwrite property_ROver
1038 @deprecated_method
1039 def convertDatum(self, datum2): # for backward compatibility
1040 '''DEPRECATED, use method L{toDatum}.'''
1041 return self.toDatum(datum2)
1043 @property_RO
1044 def _ecef9(self):
1045 return self
1047 @Property_RO
1048 def lam(self):
1049 '''Get the longitude in C{radians} (C{float}).
1050 '''
1051 return self.philam.lam
1053 @Property_RO
1054 def lamVermeille(self):
1055 '''Get the longitude in C{radians} M{[-PI*3/2..+PI*3/2]} after U{Vermeille
1056 <https://Search.ProQuest.com/docview/639493848>} (2004), page 95.
1058 @see: U{Karney<https://GeographicLib.SourceForge.io/C++/doc/geocentric.html>},
1059 U{Vermeille<https://Search.ProQuest.com/docview/847292978>} 2011, pp 112-113, 116
1060 and U{Featherstone, et.al.<https://Search.ProQuest.com/docview/872827242>}, page 7.
1061 '''
1062 x, y = self.x, self.y
1063 if y > EPS0:
1064 r = atan2(x, hypot(y, x) + y) * _N_2_0 + PI_2
1065 elif y < -EPS0:
1066 r = atan2(x, hypot(y, x) - y) * _2_0 - PI_2
1067 else: # y == 0
1068 r = PI if x < 0 else _0_0
1069 return Lam(Vermeille=r)
1071 @Property_RO
1072 def latlon(self):
1073 '''Get the lat-, longitude in C{degrees} (L{LatLon2Tuple}C{(lat, lon)}).
1074 '''
1075 return LatLon2Tuple(self.lat, self.lon, name=self.name)
1077 @Property_RO
1078 def latlonheight(self):
1079 '''Get the lat-, longitude in C{degrees} and height (L{LatLon3Tuple}C{(lat, lon, height)}).
1080 '''
1081 return self.latlon.to3Tuple(self.height)
1083 @Property_RO
1084 def latlonheightdatum(self):
1085 '''Get the lat-, longitude in C{degrees} with height and datum (L{LatLon4Tuple}C{(lat, lon, height, datum)}).
1086 '''
1087 return self.latlonheight.to4Tuple(self.datum)
1089 @Property_RO
1090 def latlonVermeille(self):
1091 '''Get the latitude and I{Vermeille} longitude in C{degrees [-225..+225]} (L{LatLon2Tuple}C{(lat, lon)}).
1093 @see: Property C{lonVermeille}.
1094 '''
1095 return LatLon2Tuple(self.lat, self.lonVermeille, name=self.name)
1097 @Property_RO
1098 def lonVermeille(self):
1099 '''Get the longitude in C{degrees [-225..+225]} after U{Vermeille
1100 <https://Search.ProQuest.com/docview/639493848>} 2004, p 95.
1102 @see: Property C{lamVermeille}.
1103 '''
1104 return Lon(Vermeille=degrees(self.lamVermeille))
1106 def _ltp_toLocal(self, ltp, Xyz_kwds, **Xyz): # overloads C{_NamedLocal}'s
1107 '''(INTERNAL) Invoke C{ltp._xLtp(ltp)._ecef2local}.
1108 '''
1109 Xyz_ = self._ltp_toLocal2(Xyz_kwds, **Xyz) # in ._NamedLocal
1110 ltp = self._ltp._xLtp(ltp, self._Ltp) # both in ._NamedLocal
1111 return ltp._ecef2local(self, *Xyz_)
1113 @Property_RO
1114 def phi(self):
1115 '''Get the latitude in C{radians} (C{float}).
1116 '''
1117 return self.philam.phi
1119 @Property_RO
1120 def philam(self):
1121 '''Get the lat-, longitude in C{radians} (L{PhiLam2Tuple}C{(phi, lam)}).
1122 '''
1123 return PhiLam2Tuple(radians(self.lat), radians(self.lon), name=self.name)
1125 @Property_RO
1126 def philamheight(self):
1127 '''Get the lat-, longitude in C{radians} and height (L{PhiLam3Tuple}C{(phi, lam, height)}).
1128 '''
1129 return self.philam.to3Tuple(self.height)
1131 @Property_RO
1132 def philamheightdatum(self):
1133 '''Get the lat-, longitude in C{radians} with height and datum (L{PhiLam4Tuple}C{(phi, lam, height, datum)}).
1134 '''
1135 return self.philamheight.to4Tuple(self.datum)
1137 @Property_RO
1138 def philamVermeille(self):
1139 '''Get the latitude and I{Vermeille} longitude in C{radians [-PI*3/2..+PI*3/2]} (L{PhiLam2Tuple}C{(phi, lam)}).
1141 @see: Property C{lamVermeille}.
1142 '''
1143 return PhiLam2Tuple(radians(self.lat), self.lamVermeille, name=self.name)
1145 phiVermeille = phi
1147 def toCartesian(self, Cartesian=None, **Cartesian_kwds):
1148 '''Return the geocentric C{(x, y, z)} coordinates as an ellipsoidal or spherical
1149 C{Cartesian}.
1151 @kwarg Cartesian: Optional class to return C{(x, y, z)} (L{ellipsoidalKarney.Cartesian},
1152 L{ellipsoidalNvector.Cartesian}, L{ellipsoidalVincenty.Cartesian},
1153 L{sphericalNvector.Cartesian} or L{sphericalTrigonometry.Cartesian})
1154 or C{None}.
1155 @kwarg Cartesian_kwds: Optionally, additional B{C{Cartesian}} keyword arguments, ignored
1156 if C{B{Cartesian} is None}.
1158 @return: A B{C{Cartesian}} instance or a L{Vector4Tuple}C{(x, y, z, h)} if C{B{Cartesian}
1159 is None}.
1161 @raise TypeError: Invalid B{C{Cartesian}} or B{C{Cartesian_kwds}} item.
1162 '''
1163 if _isin(Cartesian, None, Vector4Tuple):
1164 r = self.xyzh
1165 elif Cartesian is Vector3Tuple:
1166 r = self.xyz
1167 else:
1168 _xsubclassof(self._CartesianBase, Cartesian=Cartesian)
1169 r = Cartesian(self, **_name1__(Cartesian_kwds, _or_nameof=self))
1170 return r
1172 def toDatum(self, datum2, **name):
1173 '''Convert this C{Ecef9Tuple} to an other datum.
1175 @arg datum2: Datum to convert I{to} (L{Datum}).
1176 @kwarg name: Optional C{B{name}=NN} (C{str}).
1178 @return: The converted 9-Tuple (C{Ecef9Tuple}).
1180 @raise TypeError: The B{C{datum2}} is not a L{Datum}.
1181 '''
1182 n = _name__(name, _or_nameof=self)
1183 if _isin(self.datum, None, datum2): # PYCHOK _Names_
1184 r = self.copy(name=n)
1185 else:
1186 c = self._CartesianBase(self, datum=self.datum, name=n) # PYCHOK _Names_
1187 # c.toLatLon converts datum, x, y, z, lat, lon, etc.
1188 # and returns another Ecef9Tuple iff LatLon is None
1189 r = c.toLatLon(datum=datum2, LatLon=None)
1190 return r
1192 def toLatLon(self, LatLon=None, **LatLon_kwds):
1193 '''Return the geodetic C{(lat, lon, height[, datum])} coordinates.
1195 @kwarg LatLon: Optional class to return C{(lat, lon, height[, datum])} or C{None}.
1196 @kwarg LatLon_kwds: Optional B{C{height}}, B{C{datum}} and other B{C{LatLon}}
1197 keyword arguments.
1199 @return: A B{C{LatLon}} instance or if C{B{LatLon} is None}, a L{LatLon4Tuple}C{(lat,
1200 lon, height, datum)} or L{LatLon3Tuple}C{(lat, lon, height)} if C{datum} is
1201 specified or not.
1203 @raise TypeError: Invalid B{C{LatLon}} or B{C{LatLon_kwds}} item.
1204 '''
1205 lat, lon, D = self.lat, self.lon, self.datum # PYCHOK Ecef9Tuple
1206 kwds = _name1__(LatLon_kwds, _or_nameof=self)
1207 kwds = _xkwds(kwds, height=self.height, datum=D) # PYCHOK Ecef9Tuple
1208 d = kwds.get(_datum_, LatLon)
1209 if LatLon is None:
1210 r = LatLon3Tuple(lat, lon, kwds[_height_], name=kwds[_name_])
1211 if d is not None:
1212 # assert d is not LatLon
1213 r = r.to4Tuple(d) # checks type(d)
1214 else:
1215 if d is None:
1216 _ = kwds.pop(_datum_) # remove None datum
1217 r = LatLon(lat, lon, **kwds)
1218 _xdatum(_xattr(r, datum=D), D)
1219 return r
1221 def toVector(self, Vector=None, **Vector_kwds):
1222 '''Return these geocentric C{(x, y, z)} coordinates as vector.
1224 @kwarg Vector: Optional vector class to return C{(x, y, z)} or C{None}.
1225 @kwarg Vector_kwds: Optional, additional B{C{Vector}} keyword arguments,
1226 ignored if C{B{Vector} is None}.
1228 @return: A B{C{Vector}} instance or a L{Vector3Tuple}C{(x, y, z)} if
1229 C{B{Vector} is None}.
1231 @raise TypeError: Invalid B{C{Vector}} or B{C{Vector_kwds}} item.
1233 @see: Propertes C{xyz} and C{xyzh}
1234 '''
1235 return self.xyz if Vector is None else Vector(
1236 *self.xyz, **_name1__(Vector_kwds, _or_nameof=self)) # PYCHOK Ecef9Tuple
1238# def _T_x_M(self, T):
1239# '''(INTERNAL) Update M{self.M = T.multiply(self.M)}.
1240# '''
1241# return self.dup(M=T.multiply(self.M))
1243 @Property_RO
1244 def xyz(self):
1245 '''Get the geocentric C{(x, y, z)} coordinates (L{Vector3Tuple}C{(x, y, z)}).
1246 '''
1247 return Vector3Tuple(self.x, self.y, self.z, name=self.name)
1249 @Property_RO
1250 def xyzh(self):
1251 '''Get the geocentric C{(x, y, z)} coordinates and C{height} (L{Vector4Tuple}C{(x, y, z, h)})
1252 '''
1253 return self.xyz.to4Tuple(self.height)
1256def _4Ecef(this, Ecef): # in .datums.Datum.ecef, .ellipsoids.Ellipsoid.ecef
1257 '''Return an ECEF converter for C{this} L{Datum} or L{Ellipsoid}.
1258 '''
1259 if Ecef is None:
1260 Ecef = EcefKarney
1261 else:
1262 _xinstanceof(*_Ecefs, Ecef=Ecef)
1263 return Ecef(this, name=this.name)
1266def _llhn4(latlonh, lon, height, suffix=NN, Error=EcefError, **name): # in .ltp
1267 '''(INTERNAL) Get a C{(lat, lon, h, name)} 4-tuple.
1268 '''
1269 try:
1270 lat, lon = latlonh.lat, latlonh.lon
1271 h = _xattr(latlonh, height=_xattr(latlonh, h=height))
1272 n = _name__(name, _or_nameof=latlonh) # == latlonh._name__(name)
1273 except AttributeError:
1274 lat, h, n = latlonh, height, _name__(**name)
1275 try:
1276 return Lat(lat), Lon(lon), Height(h), n
1277 except (TypeError, ValueError) as x:
1278 t = _lat_, _lon_, _height_
1279 if suffix:
1280 t = (_ + suffix for _ in t)
1281 d = dict(zip(t, (lat, lon, h)))
1282 raise Error(cause=x, **d)
1285def _xEcef(Ecef): # PYCHOK .latlonBase
1286 '''(INTERNAL) Validate B{C{Ecef}} I{class}.
1287 '''
1288 if issubclassof(Ecef, _EcefBase):
1289 return Ecef
1290 raise _TypesError(_Ecef_, Ecef, *_Ecefs)
1293# kwd lon00 unused but will throw a TypeError if misspelled, etc.
1294def _xyzn4(xyz, y, z, Types, Error=EcefError, lon00=0, # PYCHOK unused
1295 _xyz_y_z_names=_xyz_y_z, **name): # in .ltp
1296 '''(INTERNAL) Get an C{(x, y, z, name)} 4-tuple.
1297 '''
1298 try:
1299 n = _name__(name, _or_nameof=xyz) # == xyz._name__(name)
1300 try:
1301 t = xyz.x, xyz.y, xyz.z, n
1302 if not isinstance(xyz, Types):
1303 raise _TypesError(_xyz_y_z_names[0], xyz, *Types)
1304 except AttributeError:
1305 t = map1(float, xyz, y, z) + (n,)
1306 except (TypeError, ValueError) as x:
1307 d = dict(zip(_xyz_y_z_names, (xyz, y, z)))
1308 raise Error(cause=x, **d)
1309 return t
1310# assert _xyz_y_z == _args_kwds_names(_xyzn4)[:3]
1313_Ecefs = (EcefKarney, EcefSudano, EcefVeness, EcefYou,
1314 EcefFarrell21, EcefFarrell22)
1315__all__ += _ALL_DOCS(_EcefBase)
1317# **) MIT License
1318#
1319# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved.
1320#
1321# Permission is hereby granted, free of charge, to any person obtaining a
1322# copy of this software and associated documentation files (the "Software"),
1323# to deal in the Software without restriction, including without limitation
1324# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1325# and/or sell copies of the Software, and to permit persons to whom the
1326# Software is furnished to do so, subject to the following conditions:
1327#
1328# The above copyright notice and this permission notice shall be included
1329# in all copies or substantial portions of the Software.
1330#
1331# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1332# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1333# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1334# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1335# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1336# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1337# OTHER DEALINGS IN THE SOFTWARE.