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, _EWGS84

67# from pygeodesy.ellipsoids import a_f2Tuple, _EWGS84 # 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.20'

90

91_Ecef_ = 'Ecef'

92_prolate_ = 'prolate'

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

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

95

96

97 class EcefError(_ValueError):

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

99 '''

100 pass

101

102

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

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

105 '''

106 try:

107 lat, lon = latlonh.lat, latlonh.lon

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

109 n = _xattr(latlonh, name=NN)

110 except AttributeError:

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

112

113 try:

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

115 except (TypeError, ValueError) as x:

116 t = _lat_, _lon_, _height_

117 if suffix:

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

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

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

121 return llhn

122

123

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

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

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

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

128 '''

129 try:

130 try:

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

132 if not isinstance(xyz, Types):

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

134 except AttributeError:

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

136

137 except (TypeError, ValueError) as x:

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

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

140 return t

141

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

143

144

145 class _EcefBase(_NamedBase):

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

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

148 '''

149 _datum = _WGS84

150 _E = _EWGS84

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

152

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

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

155

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

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

158 equatorial radius (C{meter}).

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

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

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

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

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

164 methods C{reverse}.

165

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

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

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

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

170 '''

171 try:

172 E = a_ellipsoid

173 if f is None:

174 if E is _EWGS84 or E is _WGS84:

175 raise AssertionError # "break"

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

177 E = a_f2Tuple(E, f)

178 else:

179 raise ValueError # _invalid_

180

181 d = _ellipsoidal_datum(E, name=name)

182 E = d.ellipsoid

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

184 raise ValueError # _invalid_

185

186 self._datum = d

187 self._E = E

188

189 except AssertionError: # "break"

190 pass

191 except (TypeError, ValueError) as x:

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

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

194

195 if name:

196 self.name = name

197 if lon00 is not INT0:

198 self.lon00 = lon00

199

200 def __eq__(self, other):

201 '''Compare this and an other Ecef.

202

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

204

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

206 '''

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

208 other.ellipsoid == self.ellipsoid)

209

210 @Property_RO

211 def equatoradius(self):

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

213 '''

214 return self.ellipsoid.a

215

216 a = equatorialRadius = equatoradius # Karney property

217

218 @Property_RO

219 def datum(self):

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

221 '''

222 return self._datum

223

224 @Property_RO

225 def ellipsoid(self):

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

227 '''

228 return self._E

229

230 @Property_RO

231 def flattening(self): # Karney property

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

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

234 '''

235 return self.ellipsoid.f

236

237 f = flattening

238

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

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

241 '''

242 if _philam: # lat, lon in radians

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

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

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

246 else:

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

248

249 E = self.ellipsoid

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

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

252 x = (h + n) * ca

253

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

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

256 0, m, self.datum,

257 name=name or self.name)

258

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

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

261

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

263 latitude (C{degrees}).

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

265 (C{degrees}).

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

267 the surface of the ellipsoid.

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

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

270

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

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

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

274 and C{datum} if available.

275

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

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

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

279

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

281 and avoid double angle conversions.

282 '''

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

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

285

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

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

288 in I{radians}.

289

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

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

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

293 the surface of the ellipsoid.

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

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

296

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

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

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

300

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

302 '''

303 try: # like function C{_llhn4} above

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

305 except (TypeError, ValueError) as x:

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

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

308

309 @property_RO

310 def _Geocentrics(self):

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

312 '''

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

314 _MODS.cartesianBase.CartesianBase)

315 return t

316

317 @Property_RO

318 def _isYou(self):

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

320 '''

321 return isinstance(self, EcefYou)

322

323 @property

324 def lon00(self):

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

326 '''

327 return self._lon00

328

329 @lon00.setter # PYCHOK setter!

330 def lon00(self, lon00):

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

332 '''

333 self._lon00 = Degrees(lon00=lon00)

334

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

336 '''Creation a rotation matrix.

337

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

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

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

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

342

343 @return: An L{EcefMatrix}.

344 '''

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

346

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

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

349 '''

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

351

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

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

354 '''

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

356

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

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

359

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

361

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

363 '''

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

365

366

367 class EcefFarrell21(_EcefBase):

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

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

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

371 '''

372

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

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

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

376 page 29.

377

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

379 coordinate (C{meter}).

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

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

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

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

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

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

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

387

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

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

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

391 if available.

392

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

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

395 zero division error.

396

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

398 '''

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

400

401 E = self.ellipsoid

402 a = E.a

403 a2 = E.a2

404 b2 = E.b2

405 e2 = E.e2

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

407 e4 = E.e4

408

409 try: # names as page 29

410 z2 = z**2

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

412

413 p = hypot(x, y)

414 p2 = p**2

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

416 F = b2 * z2 * 54

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

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

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

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

421 Q1 = Q + _1_0

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

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

424 -P * p2 * _0_5))

425 r = p + e2 * r0

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

427

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

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

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

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

432

433 except (ValueError, ZeroDivisionError) as e:

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

435

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

437 1, None, self.datum,

438 name=name or self.name)

439

440

441 class EcefFarrell22(_EcefBase):

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

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

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

445 '''

446

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

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

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

450 page 30.

451

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

453 coordinate (C{meter}).

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

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

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

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

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

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

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

461

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

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

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

465 if available.

466

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

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

469 zero division error.

470

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

472 '''

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

474

475 E = self.ellipsoid

476 a = E.a

477 b = E.b

478

479 try: # see EcefVeness.reverse

480 p = hypot(x, y)

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

482

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

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

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

486

487 s, c = sincos2d(lat)

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

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

490 else: # polar

491 h = fabs(z) - b

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

493

494 except (ValueError, ZeroDivisionError) as e:

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

496

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

498 1, None, self.datum,

499 name=name or self.name)

500

501

502 class EcefKarney(_EcefBase):

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

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

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

506

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

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

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

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

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

512 the rotation matrix.

513 '''

514

515 @Property_RO

516 def hmax(self):

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

518 '''

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

520

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

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

523

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

525 coordinate (C{meter}).

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

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

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

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

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

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

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

533

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

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

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

537 C{datum} if available.

538

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

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

541

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

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

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

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

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

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

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

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

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

551 '''

552 def _norm3(y, x):

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

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

555

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

557

558 E = self.ellipsoid

559 f = E.f

560

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

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

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

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

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

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

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

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

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

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

571 C = 1

572

573 elif E.e4: # E.isEllipsoidal

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

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

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

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

578 if f < 0:

579 p, q = q, p

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

581 e = E.e4 * q

582 if e or r > 0:

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

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

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

586 u = r = r / _6_0

587 r2 = r**2

588 r3 = r2 * r

589 t3 = r3 + s

590 d *= t3 + r3

591 if d < 0:

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

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

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

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

596 else:

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

598 # minimizes loss of precision due to cancellation. The

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

600 # in definition of u.

601 if d > 0:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

616 if f < 0:

617 k1 -= E.e2

618 else:

619 k2 += E.e2

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

621 h *= k1 - E.e21

622 C = 2

623

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

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

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

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

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

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

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

631 q = E.e4 - p

632 if f < 0:

633 p, q = q, p

634 e = E.a

635 else:

636 e = E.b2_a

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

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

639 sa = neg(sa)

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

641 C = 3

642

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

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

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

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

647 h -= E.a

648 C = 4

649

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

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

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

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

654 C, m, self.datum,

655 name=name or self.name)

656

657

658 class EcefSudano(_EcefBase):

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

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

661 '''

662 _tol = EPS2

663

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

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

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

667

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

669 coordinate (C{meter}).

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

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

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

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

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

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

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

677

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

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

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

681

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

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

684 '''

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

686

687 E = self.ellipsoid

688 e = E.e2 * E.a

689 R = hypot(x, y) # Rh

690 d = e - R

691

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

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

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

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

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

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

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

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

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

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

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

703 tol = self.tolerance

704 _S2 = Fsum(sa).fsum2_

705 for i in range(1, _TRIPS):

706 ca2 = _1_0 - sa**2

707 if ca2 < EPS_2: # PYCHOK no cover

708 ca = _0_0

709 break

710 ca = sqrt(ca2)

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

712 if fabs(r) < EPS_2:

713 break

714 lat = None

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

716 if fabs(r) < tol:

717 break

718 else:

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

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

721

722 if lat is None:

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

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

725

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

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

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

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

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

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

732 return r

733

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

735 def tolerance(self):

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

737 '''

738 return self._tol

739

740 @tolerance.setter # PYCHOK setter!

741 def tolerance(self, tol):

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

743

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

745 '''

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

747

748

749 class EcefVeness(_EcefBase):

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

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

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

753

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

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

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

757 '''

758

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

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

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

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

763

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

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

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

767

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

769 coordinate (C{meter}).

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

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

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

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

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

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

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

777

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

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

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

781

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

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

784

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

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

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

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

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

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

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

792 publication/3709199>}.

793 '''

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

795

796 E = self.ellipsoid

797

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

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

800 if min(p, r) > EPS0:

801 b = E.b * E.e22

802 # parametric latitude (Bowring eqn 17, replaced)

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

804 c = _1_0 / hypot1(t)

805 s = c * t

806

807 # geodetic latitude (Bowring eqn 18)

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

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

810

811 # height above ellipsoid (Bowring eqn 7)

812 sa, ca = sincos2d(lat)

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

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

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

816 C = 1

817

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

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

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

821

822 else: # polar lat, lon arbitrarily lon00

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

824

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

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

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

828 name=name or self.name)

829

830

831 class EcefYou(_EcefBase):

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

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

834 for I{non-prolate} ellipsoids.

835

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

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

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

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

840 '''

841

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

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

844 _ = EcefYou._e2(self.ellipsoid)

845

846 @staticmethod

847 def _e2(E):

848 e2 = E.a2 - E.b2

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

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

851 return e2

852

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

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

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

856

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

858 coordinate (C{meter}).

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

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

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

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

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

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

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

866

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

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

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

870 available.

871

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

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

874 ellipsoid is I{prolate}.

875 '''

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

877

878 E = self.ellipsoid

879 e2 = EcefYou._e2(E)

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

881

882 q = hypot( x, y) # R

883 r2 = hypot2_(x, y, z)

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

885 if u > EPS02:

886 u = sqrt(u)

887 p = hypot(u, e)

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

889 sB, cB = sincos2(B)

890 if cB and sB:

891 p *= E.a

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

893 if isnon0(d):

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

895 sB, cB = sincos2(B)

896 elif u < 0:

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

898 else:

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

900

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

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

903

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

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

906 h = neg(h) # inside ellipsoid

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

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

909 name=name or self.name)

910

911

912 class EcefMatrix(_NamedTuple):

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

914

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

916 Geographic_coordinate_conversion#From_ECEF_to_ENU>} and

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

918 '''

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

920 '_1_0_', '_1_1_', '_1_2_',

921 '_2_0_', '_2_1_', '_2_2_')

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

923

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

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

926 '''

927 _NamedTuple._validate(self, _OK=True)

928

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

930 '''New L{EcefMatrix} matrix.

931

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

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

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

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

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

937

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

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

940 '''

941 t = sa, ca, sb, cb

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

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

944

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

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

947

948 else: # build matrix from the following quaternion operations

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

950 # or

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

952 # where

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

954

955 # Local X axis (East) in geocentric coords

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

957 # Local Y axis (North) in geocentric coords

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

959 # Local Z axis (Up) in geocentric coords

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

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

962 cb, -sb * sa, sb * ca,

963 _0_0, ca, sa)

964

965 return _NamedTuple.__new__(cls, *t)

966

967 def column(self, column):

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

969 '''

970 if 0 <= column < 3:

971 return self[column::3]

972 raise _IndexError(column=column)

973

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

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

976

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

978 '''

979 return self.classof(*self)

980

981 __copy__ = __deepcopy__ = copy

982

983 @Property_RO

984 def matrix3(self):

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

986 '''

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

988

989 @Property_RO

990 def matrixTransposed3(self):

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

992 '''

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

994

995 def multiply(self, other):

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

997 with an other matrix.

998

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

1000

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

1002

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

1004 '''

1005 _xinstanceof(EcefMatrix, other=other)

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

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

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

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

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

1011

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

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

1014

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

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

1017

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

1019

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

1021 '''

1022 if xyz0:

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

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

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

1026

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

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

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

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

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

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

1033

1034 def row(self, row):

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

1036 '''

1037 if 0 <= row < 3:

1038 r = row * 3

1039 return self[r:r+3]

1040 raise _IndexError(row=row)

1041

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

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

1044

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

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

1047

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

1049

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

1051 '''

1052 if xyz0:

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

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

1055 _xyz = _1_0_1T + xyz

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

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

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

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

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

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

1062 else:

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

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

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

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

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

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

1069 return xyz_

1070

1071

1072 class Ecef9Tuple(_NamedTuple):

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

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

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

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

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

1078 '''

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

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

1081

1082 @property_RO

1083 def _CartesianBase(self):

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

1085 '''

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

1087 return C

1088

1089 @deprecated_method

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

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

1092 return self.toDatum(datum2)

1093

1094 @Property_RO

1095 def lam(self):

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

1097 '''

1098 return self.philam.lam

1099

1100 @Property_RO

1101 def lamVermeille(self):

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

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

1104

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

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

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

1108 '''

1109 x, y = self.x, self.y

1110 if y > EPS0:

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

1112 elif y < -EPS0:

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

1114 else: # y == 0

1115 r = PI if x < 0 else _0_0

1116 return Lam(Vermeille=r)

1117

1118 @Property_RO

1119 def latlon(self):

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

1121 '''

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

1123

1124 @Property_RO

1125 def latlonheight(self):

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

1127 '''

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

1129

1130 @Property_RO

1131 def latlonheightdatum(self):

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

1133 '''

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

1135

1136 @Property_RO

1137 def latlonVermeille(self):

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

1139

1140 @see: Property C{lonVermeille}.

1141 '''

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

1143

1144 @Property_RO

1145 def lonVermeille(self):

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

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

1148

1149 @see: Property C{lamVermeille}.

1150 '''

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

1152

1153 @Property_RO

1154 def phi(self):

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

1156 '''

1157 return self.philam.phi

1158

1159 @Property_RO

1160 def philam(self):

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

1162 '''

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

1164

1165 @Property_RO

1166 def philamheight(self):

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

1168 '''

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

1170

1171 @Property_RO

1172 def philamheightdatum(self):

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

1174 '''

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

1176

1177 @Property_RO

1178 def philamVermeille(self):

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

1180

1181 @see: Property C{lamVermeille}.

1182 '''

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

1184

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

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

1187 C{Cartesian}.

1188

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

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

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

1192 or C{None}.

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

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

1195

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

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

1198

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

1200 '''

1201 if Cartesian in (None, Vector4Tuple):

1202 r = self.xyzh

1203 elif Cartesian is Vector3Tuple:

1204 r = self.xyz

1205 else:

1206 _xsubclassof(self._CartesianBase, Cartesian=Cartesian)

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

1208 return r

1209

1210 def toDatum(self, datum2):

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

1212

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

1214

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

1216

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

1218 '''

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

1220 r = self.copy()

1221 else:

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

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

1224 # and returns another Ecef9Tuple iff LatLon is None

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

1226 return r

1227

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

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

1230

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

1232 or C{None}.

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

1234 B{C{LatLon}} keyword arguments.

1235

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

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

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

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

1240

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

1242 '''

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

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

1245 d = kwds.get(_datum_, LatLon)

1246 if LatLon is None:

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

1248 if d is not None:

1249 # assert d is not LatLon

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

1251 else:

1252 if d is None:

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

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

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

1256 return r

1257

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

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

1260

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

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

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

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

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

1266

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

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

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

1270

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

1272 '''

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

1274

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

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

1277

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

1279 C{None}.

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

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

1282

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

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

1285

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

1287 '''

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

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

1290

1291# def _T_x_M(self, T):

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

1293# '''

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

1295

1296 @Property_RO

1297 def xyz(self):

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

1299 '''

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

1301

1302 @Property_RO

1303 def xyzh(self):

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

1305 '''

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

1307

1308

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

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

1311 '''

1312 if Ecef is None:

1313 Ecef = EcefKarney

1314 else:

1315 _xinstanceof(*_Ecefs, Ecef=Ecef)

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

1317

1318

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

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

1321 '''

1322 if issubclassof(Ecef, _EcefBase):

1323 return Ecef

1324 raise _TypesError(_Ecef_, Ecef, *_Ecefs)

1325

1326

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

1328 EcefFarrell21, EcefFarrell22)

1329

1330__all__ += _ALL_DOCS(_EcefBase)

1331

1332# **) MIT License

1333#

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

1335#

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

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

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

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

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

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

1342#

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

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

1345#

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

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

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

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

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

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

1352# OTHER DEALINGS IN THE SOFTWARE.