Coverage for pygeodesy/ecef.py: 95%

453 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-05-29 12:40 -0400

1 

2# -*- coding: utf-8 -*- 

3 

4u'''I{Geocentric} Earth-Centered, Earth-Fixed (ECEF) coordinates. 

5 

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. 

16 

17Following is a copy of I{Karney}'s U{Detailed Description 

18<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Geocentric.html>}. 

19 

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>}). 

23 

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°. 

26 

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}. 

30 

31Forward conversion from geodetic to geocentric (ECEF) coordinates is straightforward. 

32 

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. 

36 

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. 

44 

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. 

49 

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. 

53 

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''' 

59 

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_5, _1_0, _1_0_1T, _2_0, _N_2_0, _3_0, _4_0, \ 

64 _6_0, _90_0, _N_90_0, _copysign_1_0, isnon0 # PYCHOK used! 

65from pygeodesy.datums import _ellipsoidal_datum, _WGS84, a_f2Tuple, _EWGS84 

66from pygeodesy.ecefLocals import _EcefLocal 

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, 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, _NamedTuple, _Pass, _xnamed 

78from pygeodesy.namedTuples import LatLon2Tuple, LatLon3Tuple, \ 

79 PhiLam2Tuple, Vector3Tuple, Vector4Tuple 

80from pygeodesy.props import deprecated_method, Property_RO, property_RO, \ 

81 property_ROver, property_doc_ 

82# from pygeodesy.streprs import Fmt, unstr # from .fsums 

83from pygeodesy.units import _isRadius, Degrees, Height, Int, Lam, Lat, Lon, Meter, \ 

84 Phi, Scalar, Scalar_ 

85from pygeodesy.utily import atan1, atan1d, atan2, atan2d, degrees90, degrees180, \ 

86 sincos2, sincos2_, sincos2d, sincos2d_ 

87# from pygeodesy.vector3d import Vector3d # _MODS 

88 

89from math import cos, degrees, fabs, radians, sqrt 

90 

91__all__ = _ALL_LAZY.ecef 

92__version__ = '25.05.07' 

93 

94_Ecef_ = 'Ecef' 

95_prolate_ = 'prolate' 

96_TRIPS = 33 # 8..9 sufficient, EcefSudano.reverse 

97_xyz_y_z = _xyz_, _y_, _z_ # _args_kwds_names(_xyzn4)[:3] 

98 

99 

100class EcefError(_ValueError): 

101 '''An ECEF or C{Ecef*} related issue. 

102 ''' 

103 pass 

104 

105 

106class _EcefBase(_NamedBase): 

107 '''(INTERNAL) Base class for L{EcefFarrell21}, L{EcefFarrell22}, L{EcefKarney}, 

108 L{EcefSudano}, L{EcefVeness} and L{EcefYou}. 

109 ''' 

110 _datum = _WGS84 

111 _E = _EWGS84 

112 _isYou = False 

113 _lon00 = INT0 # arbitrary, "polar" lon for LocalCartesian, Ltp 

114 

115 def __init__(self, a_ellipsoid=_EWGS84, f=None, lon00=INT0, **name): 

116 '''New C{Ecef*} converter. 

117 

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}). 

127 

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_ 

141 

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 

149 

150 except (TypeError, ValueError) as x: 

151 t = unstr(self.classname, a=a_ellipsoid, f=f) 

152 raise EcefError(_SPACE_(t, _ellipsoid_), cause=x) 

153 

154 if name: 

155 self.name = name 

156 if lon00 is not INT0: 

157 self.lon00 = lon00 

158 

159 def __eq__(self, other): 

160 '''Compare this and an other Ecef. 

161 

162 @arg other: The other ecef (C{Ecef*}). 

163 

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) 

168 

169 @Property_RO 

170 def datum(self): 

171 '''Get the datum (L{Datum}). 

172 ''' 

173 return self._datum 

174 

175 @Property_RO 

176 def ellipsoid(self): 

177 '''Get the ellipsoid (L{Ellipsoid} or L{Ellipsoid2}). 

178 ''' 

179 return self._E 

180 

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 

186 

187 a = equatorialRadius = equatoradius # Karney property 

188 

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 

195 

196 f = flattening 

197 

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) 

207 

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 

212 

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)) 

217 

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)}. 

220 

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}). 

229 

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. 

234 

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°. 

238 

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) 

244 

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}. 

248 

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}). 

255 

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})}. 

259 

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) 

267 

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 

274 

275 @property 

276 def lon00(self): 

277 '''Get the I{"polar"} longitude (C{degrees}), see method C{reverse}. 

278 ''' 

279 return self._lon00 

280 

281 @lon00.setter # PYCHOK setter! 

282 def lon00(self, lon00): 

283 '''Set the I{"polar"} longitude (C{degrees}), see method C{reverse}. 

284 ''' 

285 self._lon00 = Degrees(lon00=lon00) 

286 

287 def _Matrix(self, sa, ca, sb, cb): 

288 '''Creation a rotation matrix. 

289 

290 @arg sa: C{sin(phi)} (C{float}). 

291 @arg ca: C{cos(phi)} (C{float}). 

292 @arg sb: C{sin(lambda)} (C{float}). 

293 @arg cb: C{cos(lambda)} (C{float}). 

294 

295 @return: An L{EcefMatrix}. 

296 ''' 

297 return self._xnamed(EcefMatrix(sa, ca, sb, cb)) 

298 

299 def _polon(self, y, x, R, **lon00_name): 

300 '''(INTERNAL) Handle I{"polar"} longitude. 

301 ''' 

302 return atan2d(y, x) if R else _xkwds_get(lon00_name, lon00=self.lon00) 

303 

304 def reverse(self, xyz, y=None, z=None, M=False, **lon00_name): # PYCHOK no cover 

305 '''I{Must be overloaded}.''' 

306 self._notOverloaded(xyz, y=y, z=z, M=M, **lon00_name) 

307 

308 def toStr(self, prec=9, **unused): # PYCHOK signature 

309 '''Return this C{Ecef*} as a string. 

310 

311 @kwarg prec: Precision, number of decimal digits (0..9). 

312 

313 @return: This C{Ecef*} (C{str}). 

314 ''' 

315 return self.attrs(_a_, _f_, _datum_, _name_, prec=prec) # _ellipsoid_ 

316 

317 

318class EcefFarrell21(_EcefBase): 

319 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF) 

320 coordinates based on I{Jay A. Farrell}'s U{Table 2.1<https://Books.Google.com/ 

321 books?id=fW4foWASY6wC>}, page 29. 

322 ''' 

323 

324 def reverse(self, xyz, y=None, z=None, M=None, **lon00_name): # PYCHOK unused M 

325 '''Convert from geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)} using 

326 I{Farrell}'s U{Table 2.1<https://Books.Google.com/books?id=fW4foWASY6wC>}, 

327 page 29, aka the I{Heikkinen application} of U{Ferrari's solution 

328 <https://WikiPedia.org/wiki/Geographic_coordinate_conversion>}. 

329 

330 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x} 

331 coordinate (C{meter}). 

332 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}). 

333 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}). 

334 @kwarg M: I{Ignored}, rotation matrix C{M} not available. 

335 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument 

336 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude 

337 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}. 

338 

339 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with 

340 geodetic coordinates C{(lat, lon, height)} for the given geocentric 

341 ones C{(x, y, z)}, case C{C=1}, C{M=None} always and C{datum} 

342 if available. 

343 

344 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or B{C{z}} 

345 not C{scalar} for C{scalar} B{C{xyz}} or C{sqrt} domain or 

346 zero division error. 

347 

348 @see: L{EcefFarrell22} and L{EcefVeness}. 

349 ''' 

350 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name) 

351 

352 E = self.ellipsoid 

353 a = E.a 

354 a2 = E.a2 

355 b2 = E.b2 

356 e2 = E.e2 

357 e2_ = E.e2abs * E.a2_b2 # (E.e * E.a_b)**2 = 0.0820944... WGS84 

358 e4 = E.e4 

359 

360 try: # names as page 29 

361 z2 = z**2 

362 ez = z2 * (_1_0 - e2) # E.e2s2(z) 

363 

364 p = hypot(x, y) 

365 p2 = p**2 

366 G = p2 + ez - e2 * (a2 - b2) # p2 + ez - e4 * a2 

367 F = b2 * z2 * 54 

368 c = e4 * p2 * F / G**3 

369 s = cbrt(sqrt(c * (c + _2_0)) + c + _1_0) 

370 G *= fsumf_(s , _1_0, _1_0 / s) # k 

371 P = F / (G**2 * _3_0) 

372 Q = sqrt(_2_0 * e4 * P + _1_0) 

373 Q1 = Q + _1_0 

374 r0 = P * p * e2 / Q1 - sqrt(fsumf_(a2 * (Q1 / Q) * _0_5, 

375 -P * ez / (Q * Q1), 

376 -P * p2 * _0_5)) 

377 r = p + e2 * r0 

378 v = b2 / (sqrt(r**2 + ez) * a) # z0 / z 

379 

380 h = hypot(r, z) * (_1_0 - v) 

381 lat = atan1d((e2_ * v + _1_0) * z, p) 

382 lon = self._polon(y, x, p, **lon00_name) 

383 # note, phi and lam are swapped on page 29 

384 

385 except (ValueError, ZeroDivisionError) as X: 

386 raise EcefError(x=x, y=y, z=z, cause=X) 

387 

388 return Ecef9Tuple(x, y, z, lat, lon, h, 

389 1, None, self.datum, 

390 name=self._name__(name)) 

391 

392 

393class EcefFarrell22(_EcefBase): 

394 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF) 

395 coordinates based on I{Jay A. Farrell}'s U{Table 2.2<https://Books.Google.com/ 

396 books?id=fW4foWASY6wC>}, page 30. 

397 ''' 

398 

399 def reverse(self, xyz, y=None, z=None, M=None, **lon00_name): # PYCHOK unused M 

400 '''Convert from geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)} using 

401 I{Farrell}'s U{Table 2.2<https://Books.Google.com/books?id=fW4foWASY6wC>}, 

402 page 30. 

403 

404 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x} 

405 coordinate (C{meter}). 

406 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}). 

407 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}). 

408 @kwarg M: I{Ignored}, rotation matrix C{M} not available. 

409 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument 

410 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude 

411 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}. 

412 

413 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with 

414 geodetic coordinates C{(lat, lon, height)} for the given geocentric 

415 ones C{(x, y, z)}, case C{C=1}, C{M=None} always and C{datum} 

416 if available. 

417 

418 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or B{C{z}} 

419 not C{scalar} for C{scalar} B{C{xyz}} or C{sqrt} domain or 

420 zero division error. 

421 

422 @see: L{EcefFarrell21} and L{EcefVeness}. 

423 ''' 

424 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name) 

425 

426 E = self.ellipsoid 

427 a = E.a 

428 b = E.b 

429 

430 try: # see EcefVeness.reverse 

431 p = hypot(x, y) 

432 lon = self._polon(y, x, p, **lon00_name) 

433 

434 s, c = sincos2(atan2(z * a, p * b)) # == _norm3 

435 lat = atan1d(z + s**3 * b * E.e22, 

436 p - c**3 * a * E.e2) 

437 

438 s, c = sincos2d(lat) 

439 if c: # E.roc1_(s) = E.a / sqrt(1 - E.e2 * s**2) 

440 h = p / c - (E.roc1_(s) if s else a) 

441 else: # polar 

442 h = fabs(z) - b 

443 # note, phi and lam are swapped on page 30 

444 

445 except (ValueError, ZeroDivisionError) as e: 

446 raise EcefError(x=x, y=y, z=z, cause=e) 

447 

448 return Ecef9Tuple(x, y, z, lat, lon, h, 

449 1, None, self.datum, 

450 name=self._name__(name)) 

451 

452 

453class EcefKarney(_EcefBase): 

454 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF) 

455 coordinates transcoded from I{Karney}'s C++ U{Geocentric<https://GeographicLib.SourceForge.io/ 

456 C++/doc/classGeographicLib_1_1Geocentric.html>} methods. 

457 

458 @note: On methods C{.forward} and C{.forwar_}, let C{v} be a unit vector located 

459 at C{(lat, lon, h)}. We can express C{v} as column vectors in one of two 

460 ways, C{v1} in East, North, Up (ENU) coordinates (where the components are 

461 relative to a local coordinate system at C{C(lat0, lon0, h0)}) or as C{v0} 

462 in geocentric C{x, y, z} coordinates. Then, M{v0 = M ⋅ v1} where C{M} is 

463 the rotation matrix. 

464 ''' 

465 

466 @Property_RO 

467 def hmax(self): 

468 '''Get the distance or height limit (C{meter}, conventionally). 

469 ''' 

470 return self.equatoradius / EPS_2 # self.equatoradius * _2_EPS, 12M lighyears 

471 

472 def reverse(self, xyz, y=None, z=None, M=False, **lon00_name): 

473 '''Convert from geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)}. 

474 

475 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x} 

476 coordinate (C{meter}). 

477 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}). 

478 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}). 

479 @kwarg M: Optionally, return the rotation L{EcefMatrix} (C{bool}). 

480 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument 

481 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude 

482 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}. 

483 

484 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with 

485 geodetic coordinates C{(lat, lon, height)} for the given geocentric 

486 ones C{(x, y, z)}, case C{C}, optional C{M} (L{EcefMatrix}) and 

487 C{datum} if available. 

488 

489 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or B{C{z}} 

490 not C{scalar} for C{scalar} B{C{xyz}}. 

491 

492 @note: In general, there are multiple solutions and the result which minimizes 

493 C{height} is returned, i.e., the C{(lat, lon)} corresponding to the 

494 closest point on the ellipsoid. If there are still multiple solutions 

495 with different latitudes (applies only if C{z} = 0), then the solution 

496 with C{lat} > 0 is returned. If there are still multiple solutions with 

497 different longitudes (applies only if C{x} = C{y} = 0), then C{lon00} is 

498 returned. The returned C{lon} is in the range [−180°, 180°] and C{height} 

499 is not below M{−E.a * (1 − E.e2) / sqrt(1 − E.e2 * sin(lat)**2)}. Like 

500 C{forward} above, M{v1 = Transpose(M) ⋅ v0}. 

501 ''' 

502 def _norm3(y, x): 

503 h = hypot(y, x) # EPS0, EPS_2 

504 return (y / h, x / h, h) if h > 0 else (_0_0, _1_0, h) 

505 

506 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name) 

507 

508 E = self.ellipsoid 

509 f = E.f 

510 

511 sb, cb, R = _norm3(y, x) 

512 h = hypot(R, z) # distance to earth center 

513 if h > self.hmax: # PYCHOK no cover 

514 # We are really far away (> 12M light years). Treat the earth 

515 # as a point and h above as an acceptable approximation to the 

516 # height. This avoids overflow, e.g., in the computation of d 

517 # below. It's possible that h has overflowed to INF, that's OK. 

518 # Treat finite x, y, but R overflows to +INF by scaling by 2. 

519 sb, cb, R = _norm3(y * _0_5, x * _0_5) 

520 sa, ca, _ = _norm3(z * _0_5, R) 

521 C = 1 

522 

523 elif E.e4: # E.isEllipsoidal 

524 # Treat prolate spheroids by swapping R and Z here and by 

525 # switching the arguments to phi = atan2(...) at the end. 

526 p = (R / E.a)**2 

527 q = (z / E.a)**2 * E.e21 

528 if f < 0: 

529 p, q = q, p 

530 r = fsumf_(p, q, -E.e4) 

531 e = E.e4 * q 

532 if e or r > 0: 

533 # Avoid possible division by zero when r = 0 by multiplying 

534 # equations for s and t by r^3 and r, respectively. 

535 s = d = e * p / _4_0 # s = r^3 * s 

536 u = r = r / _6_0 

537 r2 = r**2 

538 r3 = r2 * r 

539 t3 = r3 + s 

540 d *= t3 + r3 

541 if d < 0: 

542 # t is complex, but the way u is defined, the result is real. 

543 # There are three possible cube roots. We choose the root 

544 # which avoids cancellation. Note, d < 0 implies r < 0. 

545 u += cos(atan2(sqrt(-d), -t3) / _3_0) * r * _2_0 

546 else: 

547 # Pick the sign on the sqrt to maximize abs(t3). This 

548 # minimizes loss of precision due to cancellation. The 

549 # result is unchanged because of the way the t is used 

550 # in definition of u. 

551 if d > 0: 

552 t3 += copysign0(sqrt(d), t3) # t3 = (r * t)^3 

553 # N.B. cbrt always returns the real root, cbrt(-8) = -2. 

554 t = cbrt(t3) # t = r * t 

555 if t: # t can be zero; but then r2 / t -> 0. 

556 u = fsumf_(u, t, r2 / t) 

557 v = sqrt(e + u**2) # guaranteed positive 

558 # Avoid loss of accuracy when u < 0. Underflow doesn't occur in 

559 # E.e4 * q / (v - u) because u ~ e^4 when q is small and u < 0. 

560 u = (e / (v - u)) if u < 0 else (u + v) # u+v, guaranteed positive 

561 # Need to guard against w going negative due to roundoff in u - q. 

562 w = E.e2abs * (u - q) / (_2_0 * v) 

563 # Rearrange expression for k to avoid loss of accuracy due to 

564 # subtraction. Division by 0 not possible because u > 0, w >= 0. 

565 k1 = k2 = (u / (sqrt(u + w**2) + w)) if w > 0 else sqrt(u) 

566 if f < 0: 

567 k1 -= E.e2 

568 else: 

569 k2 += E.e2 

570 sa, ca, h = _norm3(z / k1, R / k2) 

571 h *= k1 - E.e21 

572 C = 2 

573 

574 else: # e = E.e4 * q == 0 and r <= 0 

575 # This leads to k = 0 (oblate, equatorial plane) and k + E.e^2 = 0 

576 # (prolate, rotation axis) and the generation of 0/0 in the general 

577 # formulas for phi and h, using the general formula and division 

578 # by 0 in formula for h. Handle this case by taking the limits: 

579 # f > 0: z -> 0, k -> E.e2 * sqrt(q) / sqrt(E.e4 - p) 

580 # f < 0: r -> 0, k + E.e2 -> -E.e2 * sqrt(q) / sqrt(E.e4 - p) 

581 q = E.e4 - p 

582 if f < 0: 

583 p, q = q, p 

584 e = E.a 

585 else: 

586 e = E.b2_a 

587 sa, ca, h = _norm3(sqrt(q * E._1_e21), sqrt(p)) 

588 if z < 0: # for tiny negative z, not for prolate 

589 sa = neg(sa) 

590 h *= neg(e / E.e2abs) 

591 C = 3 

592 

593 else: # E.e4 == 0, spherical case 

594 # Dealing with underflow in the general case with E.e2 = 0 is 

595 # difficult. Origin maps to North pole, same as with ellipsoid. 

596 sa, ca, _ = _norm3((z if h else _1_0), R) 

597 h -= E.a 

598 C = 4 

599 

600 # lon00 <https://GitHub.com/mrJean1/PyGeodesy/issues/77> 

601 lon = self._polon(sb, cb, R, **lon00_name) 

602 m = self._Matrix(sa, ca, sb, cb) if M else None 

603 return Ecef9Tuple(x, y, z, atan1d(sa, ca), lon, h, 

604 C, m, self.datum, name=self._name__(name)) 

605 

606 

607class EcefSudano(_EcefBase): 

608 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF) coordinates 

609 based on I{John J. Sudano}'s U{paper<https://www.ResearchGate.net/publication/3709199>}. 

610 ''' 

611 _tol = EPS2 

612 

613 def reverse(self, xyz, y=None, z=None, M=None, **lon00_name): # PYCHOK unused M 

614 '''Convert from geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)} using 

615 I{Sudano}'s U{iterative method<https://www.ResearchGate.net/publication/3709199>}. 

616 

617 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x} 

618 coordinate (C{meter}). 

619 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}). 

620 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}). 

621 @kwarg M: I{Ignored}, rotation matrix C{M} not available. 

622 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument 

623 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude 

624 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}. 

625 

626 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with geodetic 

627 coordinates C{(lat, lon, height)} for the given geocentric ones C{(x, y, z)}, 

628 iteration C{C}, C{M=None} always and C{datum} if available. 

629 

630 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or B{C{z}} 

631 not C{scalar} for C{scalar} B{C{xyz}} or no convergence. 

632 ''' 

633 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name) 

634 

635 E = self.ellipsoid 

636 e = E.e2 * E.a 

637 R = hypot(x, y) # Rh 

638 d = e - R 

639 

640 lat = atan1d(z, R * E.e21) 

641 sa, ca = sincos2d(fabs(lat)) 

642 # Sudano's Eq (A-6) and (A-7) refactored/reduced, 

643 # replacing Rn from Eq (A-4) with n = E.a / ca: 

644 # N = ca**2 * ((z + E.e2 * n * sa) * ca - R * sa) 

645 # = ca**2 * (z * ca + E.e2 * E.a * sa - R * sa) 

646 # = ca**2 * (z * ca + (E.e2 * E.a - R) * sa) 

647 # D = ca**3 * (E.e2 * n / E.e2s2(sa)) - R 

648 # = ca**2 * (E.e2 * E.a / E.e2s2(sa) - R / ca**2) 

649 # N / D = (z * ca + (E.e2 * E.a - R) * sa) / 

650 # (E.e2 * E.a / E.e2s2(sa) - R / ca**2) 

651 tol = self.tolerance 

652 _S2 = Fsum(sa).fsum2f_ 

653 for i in range(1, _TRIPS): 

654 ca2 = _1_0 - sa**2 

655 if ca2 < EPS_2: # PYCHOK no cover 

656 ca = _0_0 

657 break 

658 ca = sqrt(ca2) 

659 r = e / E.e2s2(sa) - R / ca2 

660 if fabs(r) < EPS_2: 

661 break 

662 lat = None 

663 sa, t = _S2(-z * ca / r, -d * sa / r) 

664 if fabs(t) < tol: 

665 break 

666 else: 

667 t = unstr(self.reverse, x=x, y=y, z=z) 

668 raise EcefError(t, txt=Fmt.no_convergence(r, tol)) 

669 

670 if lat is None: 

671 lat = copysign0(atan1d(fabs(sa), ca), z) 

672 lon = self._polon(y, x, R, **lon00_name) 

673 

674 h = fsumf_(R * ca, fabs(z * sa), -E.a * E.e2s(sa)) # use Veness' 

675 # because Sudano's Eq (7) doesn't produce the correct height 

676 # h = (fabs(z) + R - E.a * cos(a + E.e21) * sa / ca) / (ca + sa) 

677 return Ecef9Tuple(x, y, z, lat, lon, h, 

678 i, None, self.datum, # C=i, M=None 

679 iteration=i, name=self._name__(name)) 

680 

681 @property_doc_(''' the convergence tolerance (C{float}).''') 

682 def tolerance(self): 

683 '''Get the convergence tolerance (C{scalar}). 

684 ''' 

685 return self._tol 

686 

687 @tolerance.setter # PYCHOK setter! 

688 def tolerance(self, tol): 

689 '''Set the convergence tolerance (C{scalar}). 

690 

691 @raise EcefError: Non-scalar or invalid B{C{tol}}. 

692 ''' 

693 self._tol = Scalar_(tolerance=tol, low=EPS, Error=EcefError) 

694 

695 

696class EcefVeness(_EcefBase): 

697 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF) coordinates 

698 transcoded from I{Chris Veness}' JavaScript classes U{LatLonEllipsoidal, Cartesian<https:// 

699 www.Movable-Type.co.UK/scripts/geodesy/docs/latlon-ellipsoidal.js.html>}. 

700 

701 @see: U{I{A Guide to Coordinate Systems in Great Britain}<https://www.OrdnanceSurvey.co.UK/ 

702 documents/resources/guide-coordinate-systems-great-britain.pdf>}, section I{B) Converting 

703 between 3D Cartesian and ellipsoidal latitude, longitude and height coordinates}. 

704 ''' 

705 

706 def reverse(self, xyz, y=None, z=None, M=None, **lon00_name): # PYCHOK unused M 

707 '''Conversion from geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)} 

708 transcoded from I{Chris Veness}' U{JavaScript<https://www.Movable-Type.co.UK/ 

709 scripts/geodesy/docs/latlon-ellipsoidal.js.html>}. 

710 

711 Uses B. R. Bowring’s formulation for μm precision in concise form U{I{The accuracy 

712 of geodetic latitude and height equations}<https://www.ResearchGate.net/publication/ 

713 233668213>}, Survey Review, Vol 28, 218, Oct 1985. 

714 

715 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x} 

716 coordinate (C{meter}). 

717 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}). 

718 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}). 

719 @kwarg M: I{Ignored}, rotation matrix C{M} not available. 

720 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument 

721 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude 

722 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}. 

723 

724 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with 

725 geodetic coordinates C{(lat, lon, height)} for the given geocentric 

726 ones C{(x, y, z)}, case C{C}, C{M=None} always and C{datum} if available. 

727 

728 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or B{C{z}} 

729 not C{scalar} for C{scalar} B{C{xyz}}. 

730 

731 @see: Toms, Ralph M. U{I{An Efficient Algorithm for Geocentric to Geodetic 

732 Coordinate Conversion}<https://www.OSTI.gov/scitech/biblio/110235>}, 

733 Sept 1995 and U{I{An Improved Algorithm for Geocentric to Geodetic 

734 Coordinate Conversion}<https://www.OSTI.gov/scitech/servlets/purl/231228>}, 

735 Apr 1996, both from Lawrence Livermore National Laboratory (LLNL) and 

736 Sudano, John J, U{I{An exact conversion from an Earth-centered coordinate 

737 system to latitude longitude and altitude}<https://www.ResearchGate.net/ 

738 publication/3709199>}. 

739 ''' 

740 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name) 

741 

742 E = self.ellipsoid 

743 a = E.a 

744 

745 p = hypot(x, y) # distance from minor axis 

746 r = hypot(p, z) # polar radius 

747 if min(p, r) > EPS0: 

748 b = E.b * E.e22 

749 # parametric latitude (Bowring eqn 17, replaced) 

750 t = (E.b * z) / (a * p) * (_1_0 + b / r) 

751 c = _1_0 / hypot1(t) 

752 s = c * t 

753 # geodetic latitude (Bowring eqn 18) 

754 lat = atan1d(z + s**3 * b, 

755 p - c**3 * a * E.e2) 

756 

757 # height above ellipsoid (Bowring eqn 7) 

758 sa, ca = sincos2d(lat) 

759# r = a / E.e2s(sa) # length of normal terminated by minor axis 

760# h = p * ca + z * sa - (a * a / r) 

761 h = fsumf_(p * ca, z * sa, -a * E.e2s(sa)) 

762 C = 1 

763 

764 # see <https://GIS.StackExchange.com/questions/28446> 

765 elif p > EPS: # lat arbitrarily zero, equatorial lon 

766 C, lat, h = 2, _0_0, (p - a) 

767 

768 else: # polar lat, lon arbitrarily lon00 

769 C, lat, h = 3, (_N_90_0 if z < 0 else _90_0), (fabs(z) - E.b) 

770 

771 lon = self._polon(y, x, p, **lon00_name) 

772 return Ecef9Tuple(x, y, z, lat, lon, h, 

773 C, None, self.datum, # M=None 

774 name=self._name__(name)) 

775 

776 

777class EcefYou(_EcefBase): 

778 '''Conversion between geodetic and geocentric, I{Earth-Centered, Earth-Fixed} (ECEF) coordinates 

779 using I{Rey-Jer You}'s U{transformation<https://www.ResearchGate.net/publication/240359424>} 

780 for I{non-prolate} ellipsoids. 

781 

782 @see: Featherstone, W.E., Claessens, S.J. U{I{Closed-form transformation between geodetic and 

783 ellipsoidal coordinates}<https://Espace.Curtin.edu.AU/bitstream/handle/20.500.11937/ 

784 11589/115114_9021_geod2ellip_final.pdf>} Studia Geophysica et Geodaetica, 2008, 52, 

785 pages 1-18 and U{PyMap3D <https://PyPI.org/project/pymap3d>}. 

786 ''' 

787 _isYou = True 

788 

789 def __init__(self, a_ellipsoid=_EWGS84, f=None, **lon00_name): # PYCHOK signature 

790 _EcefBase.__init__(self, a_ellipsoid, f=f, **lon00_name) # inherited documentation 

791 self._ee2 = EcefYou._ee2(self.ellipsoid) 

792 

793 @staticmethod 

794 def _ee2(E): 

795 e2 = E.a2 - E.b2 

796 if e2 < 0 or E.f < 0: 

797 raise EcefError(ellipsoid=E, txt=_prolate_) 

798 return sqrt0(e2), e2 

799 

800 def reverse(self, xyz, y=None, z=None, M=None, **lon00_name): # PYCHOK unused M 

801 '''Convert geocentric C{(x, y, z)} to geodetic C{(lat, lon, height)} 

802 using I{Rey-Jer You}'s transformation. 

803 

804 @arg xyz: A geocentric (C{Cartesian}, L{Ecef9Tuple}) or C{scalar} ECEF C{x} 

805 coordinate (C{meter}). 

806 @kwarg y: ECEF C{y} coordinate for C{scalar} B{C{xyz}} and B{C{z}} (C{meter}). 

807 @kwarg z: ECEF C{z} coordinate for C{scalar} B{C{xyz}} and B{C{y}} (C{meter}). 

808 @kwarg M: I{Ignored}, rotation matrix C{M} not available. 

809 @kwarg lon00_name: Optional C{B{name}=NN} (C{str}) and optional keyword argument 

810 C{B{lon00}=INT0} (C{degrees}), an arbitrary I{"polar"} longitude 

811 returned if C{B{x}=0} and C{B{y}=0}, see property C{lon00}. 

812 

813 @return: An L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with 

814 geodetic coordinates C{(lat, lon, height)} for the given geocentric 

815 ones C{(x, y, z)}, case C{C=1}, C{M=None} always and C{datum} if 

816 available. 

817 

818 @raise EcefError: Invalid B{C{xyz}} or C{scalar} C{x} or B{C{y}} and/or 

819 B{C{z}} not C{scalar} for C{scalar} B{C{xyz}} or the 

820 ellipsoid is I{prolate}. 

821 ''' 

822 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **lon00_name) 

823 q = hypot(x, y) # R 

824 

825 E = self.ellipsoid 

826 e, e2 = self._ee2 

827 

828 u = hypot2_(x, y, z) - e2 

829 u += hypot(u, e * z * _2_0) 

830 u *= _0_5 

831 if u > EPS02: 

832 u = sqrt(u) 

833 p = hypot(u, e) 

834 B = atan1(p * z, u * q) # beta0 = atan(p / u * z / q) 

835 sB, cB = sincos2(B) 

836 if cB and sB: 

837 p *= E.a 

838 d = (p / cB - e2 * cB) / sB 

839 if isnon0(d): 

840 B += fsumf_(u * E.b, -p, e2) / d 

841 sB, cB = sincos2(B) 

842 elif u < (-EPS2): 

843 raise EcefError(x=x, y=y, z=z, u=u, txt=_singular_) 

844 else: 

845 sB, cB = _copysign_1_0(z), _0_0 

846 

847 lat = atan1d(E.a * sB, E.b * cB) # atan(E.a_b * tan(B)) 

848 lon = self._polon(y, x, q, **lon00_name) 

849 

850 h = hypot(z - E.b * sB, q - E.a * cB) 

851 if hypot2_(x, y, z * E.a_b) < E.a2: 

852 h = neg(h) # inside ellipsoid 

853 return Ecef9Tuple(x, y, z, lat, lon, h, 

854 1, None, self.datum, # C=1, M=None 

855 name=self._name__(name)) 

856 

857 

858class EcefMatrix(_NamedTuple): 

859 '''A rotation matrix known as I{East-North-Up (ENU) to ECEF}. 

860 

861 @see: U{From ENU to ECEF<https://WikiPedia.org/wiki/ 

862 Geographic_coordinate_conversion#From_ECEF_to_ENU>} and 

863 U{Issue #74<https://Github.com/mrJean1/PyGeodesy/issues/74>}. 

864 ''' 

865 _Names_ = ('_0_0_', '_0_1_', '_0_2_', # row-order 

866 '_1_0_', '_1_1_', '_1_2_', 

867 '_2_0_', '_2_1_', '_2_2_') 

868 _Units_ = (Scalar,) * len(_Names_) 

869 

870 def _validate(self, **unused): # PYCHOK unused 

871 '''(INTERNAL) Allow C{_Names_} with leading underscore. 

872 ''' 

873 _NamedTuple._validate(self, underOK=True) 

874 

875 def __new__(cls, sa, ca, sb, cb, *_more): 

876 '''New L{EcefMatrix} matrix. 

877 

878 @arg sa: C{sin(phi)} (C{float}). 

879 @arg ca: C{cos(phi)} (C{float}). 

880 @arg sb: C{sin(lambda)} (C{float}). 

881 @arg cb: C{cos(lambda)} (C{float}). 

882 @arg _more: (INTERNAL) from C{.multiply}. 

883 

884 @raise EcefError: If B{C{sa}}, B{C{ca}}, B{C{sb}} or 

885 B{C{cb}} outside M{[-1.0, +1.0]}. 

886 ''' 

887 t = sa, ca, sb, cb 

888 if _more: # all 9 matrix elements ... 

889 t += _more # ... from .multiply 

890 

891 elif max(map(fabs, t)) > _1_0: 

892 raise EcefError(unstr(EcefMatrix, *t)) 

893 

894 else: # build matrix from the following quaternion operations 

895 # qrot(lam, [0,0,1]) * qrot(phi, [0,-1,0]) * [1,1,1,1]/2 

896 # or 

897 # qrot(pi/2 + lam, [0,0,1]) * qrot(-pi/2 + phi, [-1,0,0]) 

898 # where 

899 # qrot(t,v) = [cos(t/2), sin(t/2)*v[1], sin(t/2)*v[2], sin(t/2)*v[3]] 

900 

901 # Local X axis (East) in geocentric coords 

902 # M[0] = -slam; M[3] = clam; M[6] = 0; 

903 # Local Y axis (North) in geocentric coords 

904 # M[1] = -clam * sphi; M[4] = -slam * sphi; M[7] = cphi; 

905 # Local Z axis (Up) in geocentric coords 

906 # M[2] = clam * cphi; M[5] = slam * cphi; M[8] = sphi; 

907 t = (-sb, -cb * sa, cb * ca, 

908 cb, -sb * sa, sb * ca, 

909 _0_0, ca, sa) 

910 

911 return _NamedTuple.__new__(cls, *t) 

912 

913 def column(self, column): 

914 '''Get this matrix' B{C{column}} 0, 1 or 2 as C{3-tuple}. 

915 ''' 

916 if 0 <= column < 3: 

917 return self[column::3] 

918 raise _IndexError(column=column) 

919 

920 def copy(self, **unused): # PYCHOK signature 

921 '''Make a shallow or deep copy of this instance. 

922 

923 @return: The copy (C{This class} or subclass thereof). 

924 ''' 

925 return self.classof(*self) 

926 

927 __copy__ = __deepcopy__ = copy 

928 

929 @Property_RO 

930 def matrix3(self): 

931 '''Get this matrix' rows (C{3-tuple} of 3 C{3-tuple}s). 

932 ''' 

933 return tuple(map(self.row, range(3))) 

934 

935 @Property_RO 

936 def matrixTransposed3(self): 

937 '''Get this matrix' I{Transposed} rows (C{3-tuple} of 3 C{3-tuple}s). 

938 ''' 

939 return tuple(map(self.column, range(3))) 

940 

941 def multiply(self, other): 

942 '''Matrix multiply M{M0' ⋅ M} this matrix I{Transposed} 

943 with an other matrix. 

944 

945 @arg other: The other matrix (L{EcefMatrix}). 

946 

947 @return: The matrix product (L{EcefMatrix}). 

948 

949 @raise TypeError: If B{C{other}} is not an L{EcefMatrix}. 

950 ''' 

951 _xinstanceof(EcefMatrix, other=other) 

952 # like LocalCartesian.MatrixMultiply, C{self.matrixTransposed3 X other.matrix3} 

953 # <https://GeographicLib.SourceForge.io/C++/doc/LocalCartesian_8cpp_source.html> 

954 # X = (fdot(self.column(r), *other.column(c)) for r in (0,1,2) for c in (0,1,2)) 

955 X = (fdot(self[r::3], *other[c::3]) for r in range(3) for c in range(3)) 

956 return _xnamed(EcefMatrix(*X), typename(EcefMatrix.multiply)) 

957 

958 def rotate(self, xyz, *xyz0): 

959 '''Forward rotation M{M0' ⋅ ([x, y, z] - [x0, y0, z0])'}. 

960 

961 @arg xyz: Local C{(x, y, z)} coordinates (C{3-tuple}). 

962 @arg xyz0: Optional, local C{(x0, y0, z0)} origin (C{3-tuple}). 

963 

964 @return: Rotated C{(x, y, z)} location (C{3-tuple}). 

965 

966 @raise LenError: Unequal C{len(B{xyz})} and C{len(B{xyz0})}. 

967 ''' 

968 if xyz0: 

969 if len(xyz0) != len(xyz): 

970 raise LenError(self.rotate, xyz0=len(xyz0), xyz=len(xyz)) 

971 xyz = tuple(c - c0 for c, c0 in zip(xyz, xyz0)) 

972 

973 # x' = M[0] * x + M[3] * y + M[6] * z 

974 # y' = M[1] * x + M[4] * y + M[7] * z 

975 # z' = M[2] * x + M[5] * y + M[8] * z 

976 return (fdot(xyz, *self[0::3]), # .column(0) 

977 fdot(xyz, *self[1::3]), # .column(1) 

978 fdot(xyz, *self[2::3])) # .column(2) 

979 

980 def row(self, row): 

981 '''Get this matrix' B{C{row}} 0, 1 or 2 as C{3-tuple}. 

982 ''' 

983 if 0 <= row < 3: 

984 r = row * 3 

985 return self[r:r+3] 

986 raise _IndexError(row=row) 

987 

988 def unrotate(self, xyz, *xyz0): 

989 '''Inverse rotation M{[x0, y0, z0] + M0 ⋅ [x,y,z]'}. 

990 

991 @arg xyz: Local C{(x, y, z)} coordinates (C{3-tuple}). 

992 @arg xyz0: Optional, local C{(x0, y0, z0)} origin (C{3-tuple}). 

993 

994 @return: Unrotated C{(x, y, z)} location (C{3-tuple}). 

995 

996 @raise LenError: Unequal C{len(B{xyz})} and C{len(B{xyz0})}. 

997 ''' 

998 if xyz0: 

999 if len(xyz0) != len(xyz): 

1000 raise LenError(self.unrotate, xyz0=len(xyz0), xyz=len(xyz)) 

1001 _xyz = _1_0_1T + xyz 

1002 # x' = x0 + M[0] * x + M[1] * y + M[2] * z 

1003 # y' = y0 + M[3] * x + M[4] * y + M[5] * z 

1004 # z' = z0 + M[6] * x + M[7] * y + M[8] * z 

1005 xyz_ = (fdot(_xyz, xyz0[0], *self[0:3]), # .row(0) 

1006 fdot(_xyz, xyz0[1], *self[3:6]), # .row(1) 

1007 fdot(_xyz, xyz0[2], *self[6:9])) # .row(2) 

1008 else: 

1009 # x' = M[0] * x + M[1] * y + M[2] * z 

1010 # y' = M[3] * x + M[4] * y + M[5] * z 

1011 # z' = M[6] * x + M[7] * y + M[8] * z 

1012 xyz_ = (fdot(xyz, *self[0:3]), # .row(0) 

1013 fdot(xyz, *self[3:6]), # .row(1) 

1014 fdot(xyz, *self[6:9])) # .row(2) 

1015 return xyz_ 

1016 

1017 

1018class Ecef9Tuple(_NamedTuple, _EcefLocal): 

1019 '''9-Tuple C{(x, y, z, lat, lon, height, C, M, datum)} with I{geocentric} C{x}, 

1020 C{y} and C{z} plus I{geodetic} C{lat}, C{lon} and C{height}, case C{C} (see 

1021 the C{Ecef*.reverse} methods) and optionally, rotation matrix C{M} (L{EcefMatrix}) 

1022 and C{datum}, with C{lat} and C{lon} in C{degrees} and C{x}, C{y}, C{z} and 

1023 C{height} in C{meter}, conventionally. 

1024 ''' 

1025 _Names_ = (_x_, _y_, _z_, _lat_, _lon_, _height_, _C_, _M_, _datum_) 

1026 _Units_ = ( Meter, Meter, Meter, Lat, Lon, Height, Int, _Pass, _Pass) 

1027 

1028 @property_ROver 

1029 def _CartesianBase(self): 

1030 '''(INTERNAL) Get class C{CartesianBase}, I{once}. 

1031 ''' 

1032 return _MODS.cartesianBase.CartesianBase # overwrite property_ROver 

1033 

1034 @deprecated_method 

1035 def convertDatum(self, datum2): # for backward compatibility 

1036 '''DEPRECATED, use method L{toDatum}.''' 

1037 return self.toDatum(datum2) 

1038 

1039 @property_RO 

1040 def _ecef9(self): # in ._EcefLocal._Ltp_ecef2local 

1041 return self 

1042 

1043 @Property_RO 

1044 def lam(self): 

1045 '''Get the longitude in C{radians} (C{float}). 

1046 ''' 

1047 return self.philam.lam 

1048 

1049 @Property_RO 

1050 def lamVermeille(self): 

1051 '''Get the longitude in C{radians} M{[-PI*3/2..+PI*3/2]} after U{Vermeille 

1052 <https://Search.ProQuest.com/docview/639493848>} (2004), page 95. 

1053 

1054 @see: U{Karney<https://GeographicLib.SourceForge.io/C++/doc/geocentric.html>}, 

1055 U{Vermeille<https://Search.ProQuest.com/docview/847292978>} 2011, pp 112-113, 116 

1056 and U{Featherstone, et.al.<https://Search.ProQuest.com/docview/872827242>}, page 7. 

1057 ''' 

1058 x, y = self.x, self.y 

1059 if y > EPS0: 

1060 r = atan2(x, hypot(y, x) + y) * _N_2_0 + PI_2 

1061 elif y < -EPS0: 

1062 r = atan2(x, hypot(y, x) - y) * _2_0 - PI_2 

1063 else: # y == 0 

1064 r = PI if x < 0 else _0_0 

1065 return Lam(Vermeille=r) 

1066 

1067 @Property_RO 

1068 def latlon(self): 

1069 '''Get the lat-, longitude in C{degrees} (L{LatLon2Tuple}C{(lat, lon)}). 

1070 ''' 

1071 return LatLon2Tuple(self.lat, self.lon, name=self.name) 

1072 

1073 @Property_RO 

1074 def latlonheight(self): 

1075 '''Get the lat-, longitude in C{degrees} and height (L{LatLon3Tuple}C{(lat, lon, height)}). 

1076 ''' 

1077 return self.latlon.to3Tuple(self.height) 

1078 

1079 @Property_RO 

1080 def latlonheightdatum(self): 

1081 '''Get the lat-, longitude in C{degrees} with height and datum (L{LatLon4Tuple}C{(lat, lon, height, datum)}). 

1082 ''' 

1083 return self.latlonheight.to4Tuple(self.datum) 

1084 

1085 @Property_RO 

1086 def latlonVermeille(self): 

1087 '''Get the latitude and I{Vermeille} longitude in C{degrees [-225..+225]} (L{LatLon2Tuple}C{(lat, lon)}). 

1088 

1089 @see: Property C{lonVermeille}. 

1090 ''' 

1091 return LatLon2Tuple(self.lat, self.lonVermeille, name=self.name) 

1092 

1093 @Property_RO 

1094 def lonVermeille(self): 

1095 '''Get the longitude in C{degrees [-225..+225]} after U{Vermeille 

1096 <https://Search.ProQuest.com/docview/639493848>} 2004, p 95. 

1097 

1098 @see: Property C{lamVermeille}. 

1099 ''' 

1100 return Lon(Vermeille=degrees(self.lamVermeille)) 

1101 

1102 @Property_RO 

1103 def phi(self): 

1104 '''Get the latitude in C{radians} (C{float}). 

1105 ''' 

1106 return self.philam.phi 

1107 

1108 @Property_RO 

1109 def philam(self): 

1110 '''Get the lat-, longitude in C{radians} (L{PhiLam2Tuple}C{(phi, lam)}). 

1111 ''' 

1112 return PhiLam2Tuple(radians(self.lat), radians(self.lon), name=self.name) 

1113 

1114 @Property_RO 

1115 def philamheight(self): 

1116 '''Get the lat-, longitude in C{radians} and height (L{PhiLam3Tuple}C{(phi, lam, height)}). 

1117 ''' 

1118 return self.philam.to3Tuple(self.height) 

1119 

1120 @Property_RO 

1121 def philamheightdatum(self): 

1122 '''Get the lat-, longitude in C{radians} with height and datum (L{PhiLam4Tuple}C{(phi, lam, height, datum)}). 

1123 ''' 

1124 return self.philamheight.to4Tuple(self.datum) 

1125 

1126 @Property_RO 

1127 def philamVermeille(self): 

1128 '''Get the latitude and I{Vermeille} longitude in C{radians [-PI*3/2..+PI*3/2]} (L{PhiLam2Tuple}C{(phi, lam)}). 

1129 

1130 @see: Property C{lamVermeille}. 

1131 ''' 

1132 return PhiLam2Tuple(radians(self.lat), self.lamVermeille, name=self.name) 

1133 

1134 phiVermeille = phi 

1135 

1136 def toCartesian(self, Cartesian=None, **Cartesian_kwds): 

1137 '''Return the geocentric C{(x, y, z)} coordinates as an ellipsoidal or spherical 

1138 C{Cartesian}. 

1139 

1140 @kwarg Cartesian: Optional class to return C{(x, y, z)} (L{ellipsoidalKarney.Cartesian}, 

1141 L{ellipsoidalNvector.Cartesian}, L{ellipsoidalVincenty.Cartesian}, 

1142 L{sphericalNvector.Cartesian} or L{sphericalTrigonometry.Cartesian}) 

1143 or C{None}. 

1144 @kwarg Cartesian_kwds: Optionally, additional B{C{Cartesian}} keyword arguments, ignored 

1145 if C{B{Cartesian} is None}. 

1146 

1147 @return: A B{C{Cartesian}} instance or a L{Vector4Tuple}C{(x, y, z, h)} if C{B{Cartesian} 

1148 is None}. 

1149 

1150 @raise TypeError: Invalid B{C{Cartesian}} or B{C{Cartesian_kwds}} item. 

1151 ''' 

1152 if _isin(Cartesian, None, Vector4Tuple): 

1153 r = self.xyzh 

1154 elif Cartesian is Vector3Tuple: 

1155 r = self.xyz 

1156 else: 

1157 _xsubclassof(self._CartesianBase, Cartesian=Cartesian) 

1158 r = Cartesian(self, **_name1__(Cartesian_kwds, _or_nameof=self)) 

1159 return r 

1160 

1161 def toDatum(self, datum2, **name): 

1162 '''Convert this C{Ecef9Tuple} to an other datum. 

1163 

1164 @arg datum2: Datum to convert I{to} (L{Datum}). 

1165 @kwarg name: Optional C{B{name}=NN} (C{str}). 

1166 

1167 @return: The converted 9-Tuple (C{Ecef9Tuple}). 

1168 

1169 @raise TypeError: The B{C{datum2}} is not a L{Datum}. 

1170 ''' 

1171 n = _name__(name, _or_nameof=self) 

1172 if _isin(self.datum, None, datum2): # PYCHOK _Names_ 

1173 r = self.copy(name=n) 

1174 else: 

1175 c = self._CartesianBase(self, datum=self.datum, name=n) # PYCHOK _Names_ 

1176 # c.toLatLon converts datum, x, y, z, lat, lon, etc. 

1177 # and returns another Ecef9Tuple iff LatLon is None 

1178 r = c.toLatLon(datum=datum2, LatLon=None) 

1179 return r 

1180 

1181 def toLatLon(self, LatLon=None, **LatLon_kwds): 

1182 '''Return the geodetic C{(lat, lon, height[, datum])} coordinates. 

1183 

1184 @kwarg LatLon: Optional class to return C{(lat, lon, height[, datum])} or C{None}. 

1185 @kwarg LatLon_kwds: Optional B{C{height}}, B{C{datum}} and other B{C{LatLon}} 

1186 keyword arguments. 

1187 

1188 @return: A B{C{LatLon}} instance or if C{B{LatLon} is None}, a L{LatLon4Tuple}C{(lat, 

1189 lon, height, datum)} or L{LatLon3Tuple}C{(lat, lon, height)} if C{datum} is 

1190 specified or not. 

1191 

1192 @raise TypeError: Invalid B{C{LatLon}} or B{C{LatLon_kwds}} item. 

1193 ''' 

1194 lat, lon, D = self.lat, self.lon, self.datum # PYCHOK Ecef9Tuple 

1195 kwds = _name1__(LatLon_kwds, _or_nameof=self) 

1196 kwds = _xkwds(kwds, height=self.height, datum=D) # PYCHOK Ecef9Tuple 

1197 d = kwds.get(_datum_, LatLon) 

1198 if LatLon is None: 

1199 r = LatLon3Tuple(lat, lon, kwds[_height_], name=kwds[_name_]) 

1200 if d is not None: 

1201 # assert d is not LatLon 

1202 r = r.to4Tuple(d) # checks type(d) 

1203 else: 

1204 if d is None: 

1205 _ = kwds.pop(_datum_) # remove None datum 

1206 r = LatLon(lat, lon, **kwds) 

1207 _xdatum(_xattr(r, datum=D), D) 

1208 return r 

1209 

1210 def toVector(self, Vector=None, **Vector_kwds): 

1211 '''Return these geocentric C{(x, y, z)} coordinates as vector. 

1212 

1213 @kwarg Vector: Optional vector class to return C{(x, y, z)} or C{None}. 

1214 @kwarg Vector_kwds: Optional, additional B{C{Vector}} keyword arguments, 

1215 ignored if C{B{Vector} is None}. 

1216 

1217 @return: A B{C{Vector}} instance or a L{Vector3Tuple}C{(x, y, z)} if 

1218 C{B{Vector} is None}. 

1219 

1220 @raise TypeError: Invalid B{C{Vector}} or B{C{Vector_kwds}} item. 

1221 

1222 @see: Propertes C{xyz} and C{xyzh} 

1223 ''' 

1224 return self.xyz if Vector is None else Vector( 

1225 *self.xyz, **_name1__(Vector_kwds, _or_nameof=self)) # PYCHOK Ecef9Tuple 

1226 

1227# def _T_x_M(self, T): 

1228# '''(INTERNAL) Update M{self.M = T.multiply(self.M)}. 

1229# ''' 

1230# return self.dup(M=T.multiply(self.M)) 

1231 

1232 @Property_RO 

1233 def xyz(self): 

1234 '''Get the geocentric C{(x, y, z)} coordinates (L{Vector3Tuple}C{(x, y, z)}). 

1235 ''' 

1236 return Vector3Tuple(self.x, self.y, self.z, name=self.name) 

1237 

1238 @Property_RO 

1239 def xyzh(self): 

1240 '''Get the geocentric C{(x, y, z)} coordinates and C{height} (L{Vector4Tuple}C{(x, y, z, h)}) 

1241 ''' 

1242 return self.xyz.to4Tuple(self.height) 

1243 

1244 

1245def _4Ecef(this, Ecef): # in .datums.Datum.ecef, .ellipsoids.Ellipsoid.ecef 

1246 '''Return an ECEF converter for C{this} L{Datum} or L{Ellipsoid}. 

1247 ''' 

1248 if Ecef is None: 

1249 Ecef = EcefKarney 

1250 else: 

1251 _xinstanceof(*_Ecefs, Ecef=Ecef) 

1252 return Ecef(this, name=this.name) 

1253 

1254 

1255def _llhn4(latlonh, lon, height, suffix=NN, Error=EcefError, **name): # in .ltp 

1256 '''(INTERNAL) Get a C{(lat, lon, h, name)} 4-tuple. 

1257 ''' 

1258 try: 

1259 lat, lon = latlonh.lat, latlonh.lon 

1260 h = _xattr(latlonh, height=_xattr(latlonh, h=height)) 

1261 n = _name__(name, _or_nameof=latlonh) # == latlonh._name__(name) 

1262 except AttributeError: 

1263 lat, h, n = latlonh, height, _name__(**name) 

1264 try: 

1265 return Lat(lat), Lon(lon), Height(h), n 

1266 except (TypeError, ValueError) as x: 

1267 t = _lat_, _lon_, _height_ 

1268 if suffix: 

1269 t = (_ + suffix for _ in t) 

1270 d = dict(zip(t, (lat, lon, h))) 

1271 raise Error(cause=x, **d) 

1272 

1273 

1274def _xEcef(Ecef): # PYCHOK .latlonBase 

1275 '''(INTERNAL) Validate B{C{Ecef}} I{class}. 

1276 ''' 

1277 if issubclassof(Ecef, _EcefBase): 

1278 return Ecef 

1279 raise _TypesError(_Ecef_, Ecef, *_Ecefs) 

1280 

1281 

1282# kwd lon00 unused but will throw a TypeError if misspelled, etc. 

1283def _xyzn4(xyz, y, z, Types, Error=EcefError, lon00=0, # PYCHOK unused 

1284 _xyz_y_z_names=_xyz_y_z, **name): # in .ltp 

1285 '''(INTERNAL) Get an C{(x, y, z, name)} 4-tuple. 

1286 ''' 

1287 try: 

1288 n = _name__(name, _or_nameof=xyz) # == xyz._name__(name) 

1289 try: 

1290 t = xyz.x, xyz.y, xyz.z, n 

1291 if not isinstance(xyz, Types): 

1292 raise _TypesError(_xyz_y_z_names[0], xyz, *Types) 

1293 except AttributeError: 

1294 t = map1(float, xyz, y, z) + (n,) 

1295 except (TypeError, ValueError) as x: 

1296 d = dict(zip(_xyz_y_z_names, (xyz, y, z))) 

1297 raise Error(cause=x, **d) 

1298 return t 

1299# assert _xyz_y_z == _args_kwds_names(_xyzn4)[:3] 

1300 

1301 

1302_Ecefs = (EcefKarney, EcefSudano, EcefVeness, EcefYou, 

1303 EcefFarrell21, EcefFarrell22) 

1304__all__ += _ALL_DOCS(_EcefBase) 

1305 

1306# **) MIT License 

1307# 

1308# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved. 

1309# 

1310# Permission is hereby granted, free of charge, to any person obtaining a 

1311# copy of this software and associated documentation files (the "Software"), 

1312# to deal in the Software without restriction, including without limitation 

1313# the rights to use, copy, modify, merge, publish, distribute, sublicense, 

1314# and/or sell copies of the Software, and to permit persons to whom the 

1315# Software is furnished to do so, subject to the following conditions: 

1316# 

1317# The above copyright notice and this permission notice shall be included 

1318# in all copies or substantial portions of the Software. 

1319# 

1320# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 

1321# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

1322# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 

1323# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 

1324# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 

1325# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 

1326# OTHER DEALINGS IN THE SOFTWARE.