1

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

3

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

5

6 Geocentric conversions transcoded from I{Charles Karney}'s C++ class U{Geocentric

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

8 into pure Python class L{EcefKarney}, class L{EcefSudano} based on I{John Sudano}'s

9 U{paper<https://www.ResearchGate.net/publication/

10 3709199_An_exact_conversion_from_an_Earth-centered_coordinate_system_to_latitude_longitude_and_altitude>},

11 class L{EcefVeness} transcoded from I{Chris Veness}' JavaScript classes U{LatLonEllipsoidal,

12 Cartesian<https://www.Movable-Type.co.UK/scripts/geodesy/docs/latlon-ellipsoidal.js.html>}, class L{EcefYou}

13 implementing I{Rey-Jer You}'s U{transformations<https://www.ResearchGate.net/publication/240359424>} and

14 classes 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

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

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

19

20 Convert between geodetic coordinates C{lat}-, C{lon}gitude and height C{h} (measured vertically

21 from the surface of the ellipsoid) to geocentric C{x}, C{y} and C{z} coordinates, also known as

22 I{Earth-Centered, Earth-Fixed} (U{ECEF<https://WikiPedia.org/wiki/ECEF>}).

23

24 The origin of geocentric coordinates is at the center of the earth. The C{z} axis goes thru

25 the North pole, C{lat} = 90°. The C{x} axis goes thru C{lat} = 0°, C{lon} = 0°.

26

27 The I{local (cartesian) origin} is at (C{lat0}, C{lon0}, C{height0}). The I{local} C{x} axis points

28 East, the I{local} C{y} axis points North and the I{local} C{z} axis is normal to the ellipsoid. The

29 plane C{z = -height0} is tangent to the ellipsoid, hence the alternate name I{local tangent plane}.

30

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

32

33 For the reverse transformation we use Hugues Vermeille's U{I{Direct transformation from geocentric

34 coordinates to geodetic coordinates}<https://DOI.org/10.1007/s00190-002-0273-6>}, J. Geodesy

35(2002) 76, page 451-454.

36

37 Several changes have been made to ensure that the method returns accurate results for all finite

38 inputs (even if h is infinite). The changes are described in Appendix B of C. F. F. Karney

39 U{I{Geodesics on an ellipsoid of revolution}<https://ArXiv.org/abs/1102.1215v1>}, Feb. 2011, 85,

40 105-117 (U{preprint<https://ArXiv.org/abs/1102.1215v1>}). Vermeille similarly updated his method

41 in 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

43 coordinates<https://GeographicLib.SourceForge.io/C++/doc/geocentric.html>} for more information.

44

45 The errors in these routines are close to round-off. Specifically, for points within 5,000 Km of

46 the surface of the ellipsoid (either inside or outside the ellipsoid), the error is bounded by 7

47 nm (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)

51 longitude for I{polar} ECEF location C{x == y == 0}. Use keyword argument C{lon00} or property

52 C{lon00} to configure that value.

53

54@see: Module L{ltp} and class L{LocalCartesian}, a transcription of I{Charles Karney}'s C++ class

55 U{LocalCartesian<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1LocalCartesian.html>},

56 for conversion between geodetic and I{local cartesian} coordinates in a I{local tangent plane} as

57 opposed to I{geocentric} (ECEF) ones.

58'''

59

60 from pygeodesy.basics import copysign0, isscalar, issubclassof, neg, map1, \

61 _xinstanceof, _xsubclassof

62 from 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, isnon0 # PYCHOK used!

66 from pygeodesy.datums import a_f2Tuple, _ellipsoidal_datum, _WGS84

67# from pygeodesy.ellipsoids import a_f2Tuple # from .datums

68 from pygeodesy.errors import _IndexError, LenError, _ValueError, _TypesError, \

69 _xattr, _xdatum, _xkwds, _xkwds_get

70 from pygeodesy.fmath import cbrt, fdot, hypot, hypot1, hypot2_

71 from pygeodesy.fsums import Fsum, fsumf_

72 from pygeodesy.interns import NN, _a_, _C_, _datum_, _ellipsoid_, _f_, _height_, \

73 _lat_, _lon_, _M_, _name_, _singular_, _SPACE_, \

74 _x_, _xyz_, _y_, _z_

75 from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS

76 from pygeodesy.named import _NamedBase, _NamedTuple, notOverloaded, _Pass, _xnamed

77 from pygeodesy.namedTuples import LatLon2Tuple, LatLon3Tuple, \

78 PhiLam2Tuple, Vector3Tuple, Vector4Tuple

79 from pygeodesy.props import deprecated_method, Property_RO, property_RO, property_doc_

80 from pygeodesy.streprs import Fmt, unstr

81 from pygeodesy.units import Degrees, Height, Int, Lam, Lat, Lon, Meter, Phi, \

82 Scalar, Scalar_

83 from pygeodesy.utily import atan2d, degrees90, degrees180, sincos2, sincos2_, \

84 sincos2d, sincos2d_

85

86 from math import atan2, cos, degrees, fabs, radians, sqrt

87

88__all__ = _ALL_LAZY.ecef

89__version__ = '23.08.09'

90

91_Ecef_ = 'Ecef'

92_EWGS84 = _WGS84.ellipsoid

93_prolate_ = 'prolate'

94_TRIPS = 17 # 8..9 sufficient, EcefSudano.reverse

95_xyz_y_z = _xyz_, _y_, _z_ # _xargs_names(_xyzn4)[:3]

96

97

98 class EcefError(_ValueError):

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

100 '''

101 pass

102

103

104 def _llhn4(latlonh, lon, height, suffix=NN, Error=EcefError, name=NN): # in .ltp.LocalCartesian.forward and -.reset

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

106 '''

107 try:

108 lat, lon = latlonh.lat, latlonh.lon

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

110 n = _xattr(latlonh, name=NN)

111 except AttributeError:

112 lat, h, n = latlonh, height, NN

113

114 try:

115 llhn = Lat(lat), Lon(lon), Height(h), (name or n)

116 except (TypeError, ValueError) as x:

117 t = _lat_, _lon_, _height_

118 if suffix:

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

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

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

122 return llhn

123

124

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

126 def _xyzn4(xyz, y, z, Types, Error=EcefError, name=NN, # PYCHOK unused

127 _xyz_y_z_names=_xyz_y_z, lon00=0): # in .ltp

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

129 '''

130 try:

131 try:

132 t = xyz.x, xyz.y, xyz.z, _xattr(xyz, name=name)

133 if not isinstance(xyz, Types):

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

135 except AttributeError:

136 t = map1(float, xyz, y, z) + (name,)

137

138 except (TypeError, ValueError) as x:

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

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

141 return t

142

143# assert _xyz_y_z == _xargs_names(_xyzn4)[:3]

144

145

146 class _EcefBase(_NamedBase):

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

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

149 '''

150 _datum = _WGS84

151 _E = _EWGS84

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

153

154 def __init__(self, a_ellipsoid=_EWGS84, f=None, name=NN, lon00=INT0):

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

156

157 @arg a_ellipsoid: A (non-prolate) ellipsoid (L{Ellipsoid}, L{Ellipsoid2},

158 L{Datum} or L{a_f2Tuple}) or C{scalar} ellipsoid's

159 equatorial radius (C{meter}).

160 @kwarg f: C{None} or the ellipsoid flattening (C{scalar}), required

161 for C{scalar} B{C{a_ellipsoid}}, C{B{f}=0} represents a

162 sphere, negative B{C{f}} a prolate ellipsoid.

163 @kwarg name: Optional name (C{str}).

164 @kwarg lon00: An arbitrary, I{"polar"} longitude (C{degrees}), see the

165 methods C{reverse}.

166

167 @raise EcefError: If B{C{a_ellipsoid}} not L{Ellipsoid}, L{Ellipsoid2},

168 L{Datum} or L{a_f2Tuple} or C{scalar} or B{C{f}} not

169 C{scalar} or if C{scalar} B{C{a_ellipsoid}} not positive

170 or B{C{f}} not less than 1.0.

171 '''

172 try:

173 E = a_ellipsoid

174 if f is None:

175 if E is _EWGS84 or E is _WGS84:

176 raise AssertionError # "break"

177 elif isscalar(E) and isscalar(f):

178 E = a_f2Tuple(E, f)

179 else:

180 raise ValueError # _invalid_

181

182 d = _ellipsoidal_datum(E, name=name)

183 E = d.ellipsoid

184 if E.a < EPS or E.f > EPS1:

185 raise ValueError # _invalid_

186

187 self._datum = d

188 self._E = E

189

190 except AssertionError: # "break"

191 pass

192 except (TypeError, ValueError) as x:

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

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

195

196 if name:

197 self.name = name

198 if lon00 is not INT0:

199 self.lon00 = lon00

200

201 def __eq__(self, other):

202 '''Compare this and an other Ecef.

203

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

205

206 @return: C{True} if equal, C{False} otherwise.

207 '''

208 return other is self or (isinstance(other, self.__class__) and

209 other.ellipsoid == self.ellipsoid)

210

211 @Property_RO

212 def equatoradius(self):

213 '''Get the I{equatorial} radius, semi-axis (C{meter}).

214 '''

215 return self.ellipsoid.a

216

217 a = equatorialRadius = equatoradius # Karney property

218

219 @Property_RO

220 def datum(self):

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

222 '''

223 return self._datum

224

225 @Property_RO

226 def ellipsoid(self):

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

228 '''

229 return self._E

230

231 @Property_RO

232 def flattening(self): # Karney property

233 '''Get the I{flattening} (C{float}), M{(a - b) / a}, positive for

234 I{oblate}, negative for I{prolate} or C{0} for I{near-spherical}.

235 '''

236 return self.ellipsoid.f

237

238 f = flattening

239

240 def _forward(self, lat, lon, h, name, M=False, _philam=False): # in .ltp.LocalCartesian.forward and -.reset

241 '''(INTERNAL) Common for all C{Ecef*}.

242 '''

243 if _philam: # lat, lon in radians

244 sa, ca, sb, cb = sincos2_(lat, lon)

245 lat = Lat(degrees90( lat), Error=EcefError)

246 lon = Lon(degrees180(lon), Error=EcefError)

247 else:

248 sa, ca, sb, cb = sincos2d_(lat, lon)

249

250 E = self.ellipsoid

251 n = E.roc1_(sa, ca) if self._isYou else E.roc1_(sa)

252 z = (h + n * E.e21) * sa

253 x = (h + n) * ca

254

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

256 return Ecef9Tuple(x * cb, x * sb, z, lat, lon, h,

257 0, m, self.datum,

258 name=name or self.name)

259

260 def forward(self, latlonh, lon=None, height=0, M=False, name=NN):

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

262

263 @arg latlonh: Either a C{LatLon}, an L{Ecef9Tuple} or C{scalar}

264 latitude (C{degrees}).

265 @kwarg lon: Optional C{scalar} longitude for C{scalar} B{C{latlonh}}

266 (C{degrees}).

267 @kwarg height: Optional height (C{meter}), vertically above (or below)

268 the surface of the ellipsoid.

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

270 @kwarg name: Optional name (C{str}).

271

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

273 geocentric C{(x, y, z)} coordinates for the given geodetic ones

274 C{(lat, lon, height)}, case C{C} 0, optional C{M} (L{EcefMatrix})

275 and C{datum} if available.

276

277 @raise EcefError: If B{C{latlonh}} not C{LatLon}, L{Ecef9Tuple} or

278 C{scalar} or B{C{lon}} not C{scalar} for C{scalar}

279 B{C{latlonh}} or C{abs(lat)} exceeds 90°.

280

281 @note: Use method C{.forward_} to specify C{lat} and C{lon} in C{radians}

282 and avoid double angle conversions.

283 '''

284 llhn = _llhn4(latlonh, lon, height, name=name)

285 return self._forward(*llhn, M=M)

286

287 def forward_(self, phi, lam, height=0, M=False, name=NN):

288 '''Like method C{.forward} except with geodetic lat- and longitude given

289 in I{radians}.

290

291 @arg phi: Latitude in I{radians} (C{scalar}).

292 @arg lam: Longitude in I{radians} (C{scalar}).

293 @kwarg height: Optional height (C{meter}), vertically above (or below)

294 the surface of the ellipsoid.

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

296 @kwarg name: Optional name (C{str}).

297

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

299 with C{lat} set to C{degrees90(B{phi})} and C{lon} to

300 C{degrees180(B{lam})}.

301

302 @raise EcefError: If B{C{phi}} or B{C{lam}} invalid or not C{scalar}.

303 '''

304 try: # like function C{_llhn4} above

305 plhn = Phi(phi), Lam(lam), Height(height), name

306 except (TypeError, ValueError) as x:

307 raise EcefError(phi=phi, lam=lam, height=height, cause=x)

308 return self._forward(*plhn, M=M, _philam=True)

309

310 @property_RO

311 def _Geocentrics(self):

312 '''(INTERNAL) Get the valid geocentric classes. I{once}.

313 '''

314 _EcefBase._Geocentrics = t = (Ecef9Tuple, # overwrite property_RO

315 _MODS.cartesianBase.CartesianBase)

316 return t

317

318 @Property_RO

319 def _isYou(self):

320 '''(INTERNAL) Is this an C{EcefYou}?.

321 '''

322 return isinstance(self, EcefYou)

323

324 @property

325 def lon00(self):

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

327 '''

328 return self._lon00

329

330 @lon00.setter # PYCHOK setter!

331 def lon00(self, lon00):

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

333 '''

334 self._lon00 = Degrees(lon00=lon00)

335

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

337 '''Creation a rotation matrix.

338

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

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

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

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

343

344 @return: An L{EcefMatrix}.

345 '''

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

347

348 def _polon(self, y, x, R, **name_lon00):

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

350 '''

351 return atan2d(y, x) if R else _xkwds_get(name_lon00, lon00=self.lon00)

352

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

354 '''(INTERNAL) I{Must be overloaded}, see function C{notOverloaded}.

355 '''

356 notOverloaded(self, xyz, y=y, z=z, M=M, **name_lon00)

357

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

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

360

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

362

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

364 '''

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

366

367

368 class EcefFarrell21(_EcefBase):

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

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

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

372 '''

373

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

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

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

377 page 29.

378

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

380 coordinate (C{meter}).

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

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

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

384 @kwarg name_lon00: Optional keyword arguments C{B{name}=NN} (C{str}) and

385 I{"polar"} longitude C{B{lon00}=INT0} (C{degrees}), overriding

386 the default and property C{lon00} setting and returned if

387 C{B{x}=0} and C{B{y}=0}.

388

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

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

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

392 if available.

393

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

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

396 zero division error.

397

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

399 '''

400 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **name_lon00)

401

402 E = self.ellipsoid

403 a = E.a

404 a2 = E.a2

405 b2 = E.b2

406 e2 = E.e2

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

408 e4 = E.e4

409

410 try: # names as page 29

411 z2 = z**2

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

413

414 p = hypot(x, y)

415 p2 = p**2

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

417 F = b2 * z2 * 54

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

419 s = cbrt(_1_0 + c + sqrt(c**2 + c * 2))

420 P = F / (_3_0 * (fsumf_(_1_0, s, _1_0 / s) * G)**2)

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

422 Q1 = Q + _1_0

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

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

425 -P * p2 * _0_5))

426 r = p + e2 * r0

427 v = b2 / (sqrt(r**2 + ez) * a)

428

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

430 lat = atan2d((e2_ * v + _1_0) * z, p)

431 lon = self._polon(y, x, p, **name_lon00)

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

433

434 except (ValueError, ZeroDivisionError) as e:

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

436

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

438 1, None, self.datum,

439 name=name or self.name)

440

441

442 class EcefFarrell22(_EcefBase):

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

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

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

446 '''

447

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

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

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

451 page 30.

452

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

454 coordinate (C{meter}).

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

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

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

458 @kwarg name_lon00: Optional keyword arguments C{B{name}=NN} (C{str}) and

459 I{"polar"} longitude C{B{lon00}=INT0} (C{degrees}), overriding

460 the default and property C{lon00} setting and returned in case

461 C{B{x}=0} and C{B{y}=0}.

462

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

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

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

466 if available.

467

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

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

470 zero division error.

471

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

473 '''

474 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **name_lon00)

475

476 E = self.ellipsoid

477 a = E.a

478 b = E.b

479

480 try: # see EcefVeness.reverse

481 p = hypot(x, y)

482 lon = self._polon(y, x, p, **name_lon00)

483

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

485 lat = atan2d(z + s**3 * b * E.e22,

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

487

488 s, c = sincos2d(lat)

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

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

491 else: # polar

492 h = fabs(z) - b

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

494

495 except (ValueError, ZeroDivisionError) as e:

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

497

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

499 1, None, self.datum,

500 name=name or self.name)

501

502

503 class EcefKarney(_EcefBase):

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

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

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

507

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

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

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

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

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

513 the rotation matrix.

514 '''

515

516 @Property_RO

517 def hmax(self):

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

519 '''

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

521

522 def reverse(self, xyz, y=None, z=None, M=False, **name_lon00):

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

524

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

526 coordinate (C{meter}).

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

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

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

530 @kwarg name_lon00: Optional keyword arguments C{B{name}=NN} (C{str}) and

531 I{"polar"} longitude C{B{lon00}=INT0} (C{degrees}), overriding

532 the default and property C{lon00} setting and returned in case

533 C{B{x}=0} and C{B{y}=0}.

534

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

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

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

538 C{datum} if available.

539

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

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

542

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

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

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

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

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

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

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

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

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

552 '''

553 def _norm3(y, x):

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

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

556

557 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **name_lon00)

558

559 E = self.ellipsoid

560 f = E.f

561

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

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

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

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

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

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

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

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

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

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

572 C = 1

573

574 elif E.e4: # E.isEllipsoidal

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

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

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

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

579 if f < 0:

580 p, q = q, p

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

582 e = E.e4 * q

583 if e or r > 0:

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

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

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

587 u = r = r / _6_0

588 r2 = r**2

589 r3 = r2 * r

590 t3 = r3 + s

591 d *= t3 + r3

592 if d < 0:

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

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

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

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

597 else:

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

599 # minimizes loss of precision due to cancellation. The

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

601 # in definition of u.

602 if d > 0:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

617 if f < 0:

618 k1 -= E.e2

619 else:

620 k2 += E.e2

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

622 h *= k1 - E.e21

623 C = 2

624

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

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

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

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

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

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

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

632 q = E.e4 - p

633 if f < 0:

634 p, q = q, p

635 e = E.a

636 else:

637 e = E.b2_a

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

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

640 sa = neg(sa)

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

642 C = 3

643

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

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

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

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

648 h -= E.a

649 C = 4

650

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

652 lon = self._polon(sb, cb, R, **name_lon00)

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

654 return Ecef9Tuple(x, y, z, atan2d(sa, ca), lon, h,

655 C, m, self.datum,

656 name=name or self.name)

657

658

659 class EcefSudano(_EcefBase):

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

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

662 '''

663 _tol = EPS2

664

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

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

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

668

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

670 coordinate (C{meter}).

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

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

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

674 @kwarg name_lon00: Optional keyword arguments C{B{name}=NN} (C{str}) and

675 I{"polar"} longitude C{B{lon00}=INT0} (C{degrees}), overriding

676 the default and property C{lon00} setting and returned in case

677 C{B{x}=0} and C{B{y}=0}.

678

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

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

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

682

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

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

685 '''

686 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **name_lon00)

687

688 E = self.ellipsoid

689 e = E.e2 * E.a

690 R = hypot(x, y) # Rh

691 d = e - R

692

693 lat = atan2d(z, R * E.e21)

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

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

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

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

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

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

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

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

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

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

704 tol = self.tolerance

705 _S2 = Fsum(sa).fsum2_

706 for i in range(1, _TRIPS):

707 ca2 = _1_0 - sa**2

708 if ca2 < EPS_2: # PYCHOK no cover

709 ca = _0_0

710 break

711 ca = sqrt(ca2)

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

713 if fabs(r) < EPS_2:

714 break

715 lat = None

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

717 if fabs(r) < tol:

718 break

719 else:

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

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

722

723 if lat is None:

724 lat = copysign0(atan2d(fabs(sa), ca), z)

725 lon = self._polon(y, x, R, **name_lon00)

726

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

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

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

730 r = Ecef9Tuple(x, y, z, lat, lon, h,

731 i, None, self.datum, # M=None

732 iteration=i, name=name or self.name)

733 return r

734

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

736 def tolerance(self):

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

738 '''

739 return self._tol

740

741 @tolerance.setter # PYCHOK setter!

742 def tolerance(self, tol):

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

744

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

746 '''

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

748

749

750 class EcefVeness(_EcefBase):

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

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

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

754

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

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

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

758 '''

759

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

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

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

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

764

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

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

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

768

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

770 coordinate (C{meter}).

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

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

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

774 @kwarg name_lon00: Optional keyword arguments C{B{name}=NN} (C{str}) and

775 I{"polar"} longitude C{B{lon00}=INT0} (C{degrees}), overriding

776 the default and property C{lon00} setting and returned in case

777 C{B{x}=0} and C{B{y}=0}.

778

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

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

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

782

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

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

785

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

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

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

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

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

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

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

793 publication/3709199>}.

794 '''

795 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **name_lon00)

796

797 E = self.ellipsoid

798

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

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

801 if min(p, r) > EPS0:

802 b = E.b * E.e22

803 # parametric latitude (Bowring eqn 17, replaced)

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

805 c = _1_0 / hypot1(t)

806 s = c * t

807

808 # geodetic latitude (Bowring eqn 18)

809 lat = atan2d(z + b * s**3,

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

811

812 # height above ellipsoid (Bowring eqn 7)

813 sa, ca = sincos2d(lat)

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

815# h = p * ca + z * sa - (E.a * E.a / r)

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

817 C = 1

818

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

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

821 C, lat, h = 2, _0_0, (p - E.a)

822

823 else: # polar lat, lon arbitrarily lon00

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

825

826 lon = self._polon(y, x, p, **name_lon00)

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

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

829 name=name or self.name)

830

831

832 class EcefYou(_EcefBase):

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

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

835 for I{non-prolate} ellipsoids.

836

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

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

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

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

841 '''

842

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

844 _EcefBase.__init__(self, a_ellipsoid, f=f, **name_lon00) # inherited documentation

845 _ = EcefYou._e2(self.ellipsoid)

846

847 @staticmethod

848 def _e2(E):

849 e2 = E.a2 - E.b2

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

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

852 return e2

853

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

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

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

857

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

859 coordinate (C{meter}).

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

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

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

863 @kwarg name_lon00: Optional keyword arguments C{B{name}=NN} (C{str}) and

864 I{"polar"} longitude C{B{lon00}=INT0} (C{degrees}), overriding

865 the default and property C{lon00} setting and returned in case

866 C{B{x}=0} and C{B{y}=0}.

867

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

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

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

871 available.

872

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

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

875 ellipsoid is I{prolate}.

876 '''

877 x, y, z, name = _xyzn4(xyz, y, z, self._Geocentrics, **name_lon00)

878

879 E = self.ellipsoid

880 e2 = EcefYou._e2(E)

881 e = sqrt(e2) if e2 > 0 else _0_0 # XXX sqrt0(e2)?

882

883 q = hypot( x, y) # R

884 r2 = hypot2_(x, y, z)

885 u = fsumf_(r2, -e2, hypot(r2 - e2, e * z * _2_0)) * _0_5

886 if u > EPS02:

887 u = sqrt(u)

888 p = hypot(u, e)

889 B = atan2(p * z, u * q) # beta0 = atan(p / u * z / q)

890 sB, cB = sincos2(B)

891 if cB and sB:

892 p *= E.a

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

894 if isnon0(d):

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

896 sB, cB = sincos2(B)

897 elif u < 0:

898 raise EcefError(x=x, y=y, z=z, txt=_singular_)

899 else:

900 sB, cB = (_N_1_0 if z < 0 else _1_0), _0_0

901

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

903 lon = self._polon(y, x, q, **name_lon00)

904

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

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

907 h = neg(h) # inside ellipsoid

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

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

910 name=name or self.name)

911

912

913 class EcefMatrix(_NamedTuple):

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

915

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

917 Geographic_coordinate_conversion#From_ECEF_to_ENU>} and

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

919 '''

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

921 '_1_0_', '_1_1_', '_1_2_',

922 '_2_0_', '_2_1_', '_2_2_')

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

924

925 def _validate(self, **_OK): # PYCHOK unused

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

927 '''

928 _NamedTuple._validate(self, _OK=True)

929

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

931 '''New L{EcefMatrix} matrix.

932

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

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

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

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

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

938

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

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

941 '''

942 t = sa, ca, sb, cb

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

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

945

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

947 raise EcefError(unstr(EcefMatrix.__name__, *t))

948

949 else: # build matrix from the following quaternion operations

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

951 # or

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

953 # where

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

955

956 # Local X axis (East) in geocentric coords

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

958 # Local Y axis (North) in geocentric coords

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

960 # Local Z axis (Up) in geocentric coords

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

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

963 cb, -sb * sa, sb * ca,

964 _0_0, ca, sa)

965

966 return _NamedTuple.__new__(cls, *t)

967

968 def column(self, column):

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

970 '''

971 if 0 <= column < 3:

972 return self[column::3]

973 raise _IndexError(column=column)

974

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

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

977

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

979 '''

980 return self.classof(*self)

981

982 __copy__ = __deepcopy__ = copy

983

984 @Property_RO

985 def matrix3(self):

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

987 '''

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

989

990 @Property_RO

991 def matrixTransposed3(self):

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

993 '''

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

995

996 def multiply(self, other):

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

998 with an other matrix.

999

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

1001

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

1003

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

1005 '''

1006 _xinstanceof(EcefMatrix, other=other)

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

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

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

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

1011 return _xnamed(EcefMatrix(*X), EcefMatrix.multiply.__name__)

1012

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

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

1015

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

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

1018

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

1020

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

1022 '''

1023 if xyz0:

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

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

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

1027

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

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

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

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

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

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

1034

1035 def row(self, row):

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

1037 '''

1038 if 0 <= row < 3:

1039 r = row * 3

1040 return self[r:r+3]

1041 raise _IndexError(row=row)

1042

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

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

1045

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

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

1048

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

1050

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

1052 '''

1053 if xyz0:

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

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

1056 _xyz = _1_0_1T + xyz

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

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

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

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

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

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

1063 else:

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

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

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

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

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

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

1070 return xyz_

1071

1072

1073 class Ecef9Tuple(_NamedTuple):

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

1075 C{x}, C{y} and C{z} plus I{geodetic} C{lat}, C{lon} and C{height}, case

1076 C{C} (see the C{Ecef*.reverse} methods) and optionally, the rotation

1077 matrix C{M} (L{EcefMatrix}) and C{datum}, with C{lat} and C{lon} in

1078 C{degrees} and C{x}, C{y}, C{z} and C{height} in C{meter}, conventionally.

1079 '''

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

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

1082

1083 @property_RO

1084 def _CartesianBase(self):

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

1086 '''

1087 Ecef9Tuple._CartesianBase = C = _MODS.cartesianBase.CartesianBase # overwrite property_RO

1088 return C

1089

1090 @deprecated_method

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

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

1093 return self.toDatum(datum2)

1094

1095 @Property_RO

1096 def lam(self):

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

1098 '''

1099 return self.philam.lam

1100

1101 @Property_RO

1102 def lamVermeille(self):

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

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

1105

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

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

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

1109 '''

1110 x, y = self.x, self.y

1111 if y > EPS0:

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

1113 elif y < -EPS0:

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

1115 else: # y == 0

1116 r = PI if x < 0 else _0_0

1117 return Lam(Vermeille=r)

1118

1119 @Property_RO

1120 def latlon(self):

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

1122 '''

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

1124

1125 @Property_RO

1126 def latlonheight(self):

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

1128 '''

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

1130

1131 @Property_RO

1132 def latlonheightdatum(self):

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

1134 '''

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

1136

1137 @Property_RO

1138 def latlonVermeille(self):

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

1140

1141 @see: Property C{lonVermeille}.

1142 '''

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

1144

1145 @Property_RO

1146 def lonVermeille(self):

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

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

1149

1150 @see: Property C{lamVermeille}.

1151 '''

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

1153

1154 @Property_RO

1155 def phi(self):

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

1157 '''

1158 return self.philam.phi

1159

1160 @Property_RO

1161 def philam(self):

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

1163 '''

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

1165

1166 @Property_RO

1167 def philamheight(self):

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

1169 '''

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

1171

1172 @Property_RO

1173 def philamheightdatum(self):

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

1175 '''

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

1177

1178 @Property_RO

1179 def philamVermeille(self):

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

1181

1182 @see: Property C{lamVermeille}.

1183 '''

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

1185

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

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

1188 C{Cartesian}.

1189

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

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

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

1193 or C{None}.

1194 @kwarg Cartesian_kwds: Optional, additional B{C{Cartesian}} keyword arguments, ignored

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

1196

1197 @return: A C{B{Cartesian}(x, y, z, **B{Cartesian_kwds})} instance or

1198 a L{Vector4Tuple}C{(x, y, z, h)} if C{B{Cartesian} is None}.

1199

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

1201 '''

1202 if Cartesian in (None, Vector4Tuple):

1203 r = self.xyzh

1204 elif Cartesian is Vector3Tuple:

1205 r = self.xyz

1206 else:

1207 _xsubclassof(self._CartesianBase, Cartesian=Cartesian)

1208 r = Cartesian(self, **_xkwds(Cartesian_kwds, name=self.name))

1209 return r

1210

1211 def toDatum(self, datum2):

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

1213

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

1215

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

1217

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

1219 '''

1220 if self.datum in (None, datum2): # PYCHOK _Names_

1221 r = self.copy()

1222 else:

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

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

1225 # and returns another Ecef9Tuple iff LatLon is None

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

1227 return r

1228

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

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

1231

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

1233 or C{None}.

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

1235 B{C{LatLon}} keyword arguments.

1236

1237 @return: An instance of C{B{LatLon}(lat, lon, **B{LatLon_kwds})}

1238 or if B{C{LatLon}} is C{None}, a L{LatLon3Tuple}C{(lat, lon,

1239 height)} respectively L{LatLon4Tuple}C{(lat, lon, height,

1240 datum)} depending on whether C{datum} is un-/specified.

1241

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

1243 '''

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

1245 kwds = _xkwds(LatLon_kwds, height=self.height, datum=D, name=self.name) # PYCHOK Ecef9Tuple

1246 d = kwds.get(_datum_, LatLon)

1247 if LatLon is None:

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

1249 if d is not None:

1250 # assert d is not LatLon

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

1252 else:

1253 if d is None:

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

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

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

1257 return r

1258

1259 def toLocal(self, ltp, Xyz=None, **Xyz_kwds):

1260 '''Convert this geocentric to I{local} C{x}, C{y} and C{z}.

1261

1262 @kwarg ltp: The I{local tangent plane} (LTP) to use (L{Ltp}).

1263 @kwarg Xyz: Optional class to return C{x}, C{y} and C{z}

1264 (L{XyzLocal}, L{Enu}, L{Ned}) or C{None}.

1265 @kwarg Xyz_kwds: Optional, additional B{C{Xyz}} keyword

1266 arguments, ignored if C{B{Xyz} is None}.

1267

1268 @return: An B{C{Xyz}} instance or if C{B{Xyz} is None},

1269 a L{Local9Tuple}C{(x, y, z, lat, lon, height,

1270 ltp, ecef, M)} with C{M=None}, always.

1271

1272 @raise TypeError: Invalid B{C{ltp}}.

1273 '''

1274 return _MODS.ltp._xLtp(ltp)._ecef2local(self, Xyz, Xyz_kwds)

1275

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

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

1278

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

1280 C{None}.

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

1282 arguments, ignored if C{B{Vector} is None}.

1283

1284 @return: A C{Vector}C{(x, y, z, **Vector_kwds)} instance or a

1285 L{Vector3Tuple}C{(x, y, z)} if B{C{Vector}} is C{None}.

1286

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

1288 '''

1289 return self.xyz if Vector is None else self._xnamed(

1290 Vector(self.x, self.y, self.z, **Vector_kwds)) # PYCHOK Ecef9Tuple

1291

1292# def _T_x_M(self, T):

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

1294# '''

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

1296

1297 @Property_RO

1298 def xyz(self):

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

1300 '''

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

1302

1303 @Property_RO

1304 def xyzh(self):

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

1306 '''

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

1308

1309

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

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

1312 '''

1313 if Ecef is None:

1314 Ecef = EcefKarney

1315 else:

1316 _xinstanceof(*_Ecefs, Ecef=Ecef)

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

1318

1319

1320 def _xEcef(Ecef): # PYCHOK .latlonBase.py

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

1322 '''

1323 if issubclassof(Ecef, _EcefBase):

1324 return Ecef

1325 raise _TypesError(_Ecef_, Ecef, *_Ecefs)

1326

1327

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

1329 EcefFarrell21, EcefFarrell22)

1330

1331__all__ += _ALL_DOCS(_EcefBase)

1332

1333# **) MIT License

1334#

1335# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved.

1336#

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

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

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

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

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

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

1343#

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

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

1346#

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

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

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

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

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

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

1353# OTHER DEALINGS IN THE SOFTWARE.