Coverage for pygeodesy/latlonBase.py: 93%

1

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

3

4 u'''(INTERNAL) Base class L{LatLonBase} for all elliposiodal, spherical and N-vectorial C{LatLon} classes.

5

6@see: I{(C) Chris Veness 2005-2024}' U{latlong<https://www.Movable-Type.co.UK/scripts/latlong.html>},

7 U{-ellipsoidal<https://www.Movable-Type.co.UK/scripts/geodesy/docs/latlon-ellipsoidal.js.html>} and

8 U{-vectors<https://www.Movable-Type.co.UK/scripts/latlong-vectors.html>} and I{Charles Karney}'s

9 U{Rhumb<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Rhumb.html>} and

10 U{RhumbLine<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1RhumbLine.html>} classes.

11'''

12

13 from pygeodesy.basics import _isin, isstr, map1, _xinstanceof

14 from pygeodesy.constants import EPS, EPS0, EPS1, EPS4, INT0, R_M, \

15 _EPSqrt as _TOL, _0_0, _0_5, _1_0, \

16 _360_0, _umod_360

17 from pygeodesy.datums import _spherical_datum

18 from pygeodesy.dms import F_D, F_DMS, latDMS, lonDMS, parse3llh

19# from pygeodesy.ecef import EcefKarney # _MODS

20 from pygeodesy.ecefLocals import _EcefLocal

21 from pygeodesy.errors import _AttributeError, IntersectionError, \

22 _incompatible, _IsnotError, _TypeError, \

23 _ValueError, _xattr, _xdatum, _xError, \

24 _xkwds, _xkwds_get, _xkwds_item2, _xkwds_not

25# from pygeodesy.fmath import favg # _MODS

26# from pygeodesy import formy as _formy # _MODS.into

27 from pygeodesy.internals import _passarg, typename

28 from pygeodesy.interns import NN, _COMMASPACE_, _concentric_, _intersection_, \

29 _LatLon_, _m_, _no_, _overlap_, _point_ # PYCHOK used!

30# from pygeodesy.iters import PointsIter, points2 # _MODS

31# from pygeodesy.karney import Caps # _MODS

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

33 from pygeodesy.named import _name2__, _NamedBase, Fmt

34 from pygeodesy.namedTuples import Bounds2Tuple, LatLon2Tuple, PhiLam2Tuple, \

35 Trilaterate5Tuple, Vector3Tuple

36# from pygeodesy.nvectorBase import _N_Vector # _MODS

37 from pygeodesy.props import deprecated_method, Property, Property_RO, \

38 property_RO, _update_all

39# from pygeodesy.streprs import Fmt, hstr # from .named, _MODS

40 from pygeodesy.units import _isDegrees, _isRadius, Distance_, Lat, Lon, \

41 Height, Radius, Radius_, Scalar, Scalar_

42 from pygeodesy.utily import sincos2d_, _unrollon, _unrollon3, _Wrap

43# from pygeodesy.vector2d import _circin6, Circin6Tuple, _circum3, circum4_, \

44# Circum3Tuple, _radii11ABC4 # _MODS

45# from pygeodesy.vector3d import nearestOn6, Vector3d # _MODS

46

47 from contextlib import contextmanager

48 from math import asin, cos, degrees, fabs, radians

49

50 __all__ = _ALL_LAZY.latlonBase

51 __version__ = '25.08.18'

52

53 _formy = _MODS.into(formy=__name__)

54

55

56 class LatLonBase(_NamedBase, _EcefLocal):

57 '''(INTERNAL) Base class for ellipsoidal and spherical C{satLon}s.

58 '''

59 _clipid = INT0 # polygonal clip, see .booleans

60 _datum = None # L{Datum}, to be overriden

61 _height = INT0 # height (C{meter}), default

62 _lat = 0 # latitude (C{degrees})

63 _lon = 0 # longitude (C{degrees})

64

65 def __init__(self, lat_llh, lon=None, height=0, datum=None, **wrap_name):

66 '''New C{LatLon}.

67

68 @arg lat_llh: Latitude (C{degrees} or DMS C{str} with N or S suffix) or

69 a previous C{LatLon} instance provided C{B{lon}=None}.

70 @kwarg lon: Longitude (C{degrees} or DMS C{str} with E or W suffix),

71 required if B{C{lat_llh}} is C{degrees} or C{str}.

72 @kwarg height: Optional height above (or below) the earth surface

73 (C{meter}, conventionally).

74 @kwarg datum: Optional datum (L{Datum}, L{Ellipsoid}, L{Ellipsoid2},

75 L{a_f2Tuple} or I{scalar} radius) or C{None}.

76 @kwarg wrap_name: Optional C{B{name}=NN} (C{str}) and optional keyword

77 argument C{B{wrap}=False}, if C{True}, wrap or I{normalize}

78 B{C{lat}} and B{C{lon}} (C{bool}).

79

80 @return: New instance (C{LatLon}).

81

82 @raise RangeError: A B{C{lon}} or C{lat} value outside the valid

83 range and L{rangerrors} set to C{True}.

84

85 @raise TypeError: If B{C{lat_llh}} is not a C{LatLon}.

86

87 @raise UnitError: Invalid C{lat}, B{C{lon}} or B{C{height}}.

88 '''

89 w, n = self._wrap_name2(**wrap_name)

90 if n:

91 self.name = n

92

93 if lon is None:

94 lat, lon, height = _latlonheight3(lat_llh, height, w)

95 elif w:

96 lat, lon = _Wrap.latlonDMS2(lat_llh, lon)

97 else:

98 lat = lat_llh

99

100 self._lat = Lat(lat) # parseDMS2(lat, lon)

101 self._lon = Lon(lon) # PYCHOK LatLon2Tuple

102 if height: # elevation

103 self._height = Height(height)

104 if datum is not None:

105 self._datum = _spherical_datum(datum, name=self.name)

106

107 def __eq__(self, other):

108 return self.isequalTo(other)

109

110 def __ne__(self, other):

111 return not self.isequalTo(other)

112

113 def __str__(self):

114 return self.toStr(form=F_D, prec=6)

115

116 def antipode(self, height=None):

117 '''Return the antipode, the point diametrically opposite to

118 this point.

119

120 @kwarg height: Optional height of the antipode (C{meter}),

121 this point's height otherwise.

122

123 @return: The antipodal point (C{LatLon}).

124 '''

125 a = _formy.antipode(*self.latlon)

126 h = self._heigHt(height)

127 return self.classof(*a, height=h)

128

129 @deprecated_method

130 def bounds(self, wide, tall, radius=R_M): # PYCHOK no cover

131 '''DEPRECATED, use method C{boundsOf}.'''

132 return self.boundsOf(wide, tall, radius=radius)

133

134 def boundsOf(self, wide, tall, radius=R_M, height=None, **name):

135 '''Return the SW and NE lat-/longitude of a great circle

136 bounding box centered at this location.

137

138 @arg wide: Longitudinal box width (C{meter}, same units as

139 B{C{radius}} or C{degrees} if C{B{radius} is None}).

140 @arg tall: Latitudinal box size (C{meter}, same units as

141 B{C{radius}} or C{degrees} if C{B{radius} is None}).

142 @kwarg radius: Mean earth radius (C{meter}) or C{None} if I{both}

143 B{C{wide}} and B{C{tall}} are in C{degrees}.

144 @kwarg height: Height for C{latlonSW} and C{latlonNE} (C{meter}),

145 overriding the point's height.

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

147

148 @return: A L{Bounds2Tuple}C{(latlonSW, latlonNE)}, the lower-left

149 and upper-right corner (C{LatLon}).

150

151 @see: U{https://www.Movable-Type.co.UK/scripts/latlong-db.html}

152 '''

153 w = Scalar_(wide=wide) * _0_5

154 t = Scalar_(tall=tall) * _0_5

155 if radius is not None:

156 r = Radius_(radius)

157 c = cos(self.phi)

158 w = degrees(asin(w / r) / c) if fabs(c) > EPS0 else _0_0 # XXX

159 t = degrees(t / r)

160 y, t = self.lat, fabs(t)

161 x, w = self.lon, fabs(w)

162

163 h = self._heigHt(height)

164 sw = self.classof(y - t, x - w, height=h)

165 ne = self.classof(y + t, x + w, height=h)

166 return Bounds2Tuple(sw, ne, name=self._name__(name))

167

168 def chordTo(self, other, height=None, wrap=False):

169 '''Compute the length of the chord through the earth between

170 this and an other point.

171

172 @arg other: The other point (C{LatLon}).

173 @kwarg height: Overriding height for both points (C{meter}),

174 or if C{None}, use each point's height.

175 @kwarg wrap: If C{True}, wrap or I{normalize} the B{C{other}}

176 point (C{bool}).

177

178 @return: The chord length (conventionally C{meter}).

179

180 @raise TypeError: The B{C{other}} point is not C{LatLon}.

181 '''

182 def _v3d(ll, V3d=_MODS.vector3d.Vector3d):

183 t = ll.toEcef(height=height) # .toVector(Vector=V3d)

184 return V3d(t.x, t.y, t.z)

185

186 p = self.others(other)

187 if wrap:

188 p = _Wrap.point(p)

189 return _v3d(self).minus(_v3d(p)).length

190

191 def circin6(self, point2, point3, eps=EPS4, **wrap_name):

192 '''Return the radius and center of the I{inscribed} aka I{In-}circle

193 of the (planar) triangle formed by this and two other points.

194

195 @arg point2: Second point (C{LatLon}).

196 @arg point3: Third point (C{LatLon}).

197 @kwarg eps: Tolerance for function L{pygeodesy.trilaterate3d2}.

198 @kwarg wrap_name: Optional C{B{name}=NN} (C{str}) and optional keyword

199 argument C{B{wrap}=False}, if C{True}, wrap or I{normalize}

200 the B{C{points}} (C{bool}).

201

202 @return: A L{Circin6Tuple}C{(radius, center, deltas, cA, cB, cC)}. The

203 C{center} and contact points C{cA}, C{cB} and C{cC}, each an

204 instance of this (sub-)class, are co-planar with this and the

205 two given points, see the B{Note} below.

206

207 @raise ImportError: Package C{numpy} not found, not installed or older

208 than version 1.10.

209

210 @raise IntersectionError: Near-coincident or -colinear points or

211 a trilateration or C{numpy} issue.

212

213 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}.

214

215 @note: The C{center} is trilaterated in cartesian (ECEF) space and converted

216 back to geodetic lat-, longitude and height. The latter, conventionally

217 in C{meter} indicates whether the C{center} is above, below or on the

218 surface of the earth model. If C{deltas} is C{None}, the C{center} is

219 I{un}ambigous. Otherwise C{deltas} is a L{LatLon3Tuple}C{(lat, lon,

220 height)} representing the differences between both results from

221 L{pygeodesy.trilaterate3d2} and C{center} is the mean thereof.

222

223 @see: Function L{pygeodesy.circin6}, method L{circum3}, U{Incircle

224 <https://MathWorld.Wolfram.com/Incircle.html>} and U{Contact Triangle

225 <https://MathWorld.Wolfram.com/ContactTriangle.html>}.

226 '''

227 w, n = self._wrap_name2(**wrap_name)

228

229 with _toCartesian3(self, point2, point3, w) as cs:

230 m = _MODS.vector2d

231 r, c, d, A, B, C = m._circin6(*cs, eps=eps, useZ=True, dLL3=True,

232 datum=self.datum) # PYCHOK unpack

233 return m.Circin6Tuple(r, c.toLatLon(), d, A.toLatLon(),

234 B.toLatLon(),

235 C.toLatLon(), name=n)

236

237 def circum3(self, point2, point3, circum=True, eps=EPS4, **wrap_name):

238 '''Return the radius and center of the smallest circle I{through} or I{containing}

239 this and two other points.

240

241 @arg point2: Second point (C{LatLon}).

242 @arg point3: Third point (C{LatLon}).

243 @kwarg circum: If C{True}, return the C{circumradius} and C{circumcenter},

244 always, ignoring the I{Meeus}' Type I case (C{bool}).

245 @kwarg eps: Tolerance for function L{pygeodesy.trilaterate3d2}.

246 @kwarg wrap_name: Optional C{B{name}=NN} (C{str}) and optional keyword

247 argument C{B{wrap}=False}, if C{True}, wrap or I{normalize}

248 the B{C{points}} (C{bool}).

249

250 @return: A L{Circum3Tuple}C{(radius, center, deltas)}. The C{center}, an

251 instance of this (sub-)class, is co-planar with this and the two

252 given points. If C{deltas} is C{None}, the C{center} is

253 I{un}ambigous. Otherwise C{deltas} is a L{LatLon3Tuple}C{(lat,

254 lon, height)} representing the difference between both results

255 from L{pygeodesy.trilaterate3d2} and C{center} is the mean thereof.

256

257 @raise ImportError: Package C{numpy} not found, not installed or older than

258 version 1.10.

259

260 @raise IntersectionError: Near-concentric, -coincident or -colinear points,

261 incompatible C{Ecef} classes or a trilateration

262 or C{numpy} issue.

263

264 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}.

265

266 @note: The C{center} is trilaterated in cartesian (ECEF) space and converted

267 back to geodetic lat-, longitude and height. The latter, conventionally

268 in C{meter} indicates whether the C{center} is above, below or on the

269 surface of the earth model. If C{deltas} is C{None}, the C{center} is

270 I{un}ambigous. Otherwise C{deltas} is a L{LatLon3Tuple}C{(lat, lon,

271 height)} representing the difference between both results from

272 L{pygeodesy.trilaterate3d2} and C{center} is the mean thereof.

273

274 @see: Function L{pygeodesy.circum3} and methods L{circin6} and L{circum4_}.

275 '''

276 w, n = self._wrap_name2(**wrap_name)

277

278 with _toCartesian3(self, point2, point3, w, circum=circum) as cs:

279 m = _MODS.vector2d

280 r, c, d = m._circum3(*cs, circum=circum, eps=eps, useZ=True, dLL3=True, # XXX -3d2

281 clas=cs[0].classof, datum=self.datum) # PYCHOK unpack

282 return m.Circum3Tuple(r, c.toLatLon(), d, name=n)

283

284 def circum4_(self, *points, **wrap_name):

285 '''Best-fit a sphere through this and two or more other points.

286

287 @arg points: The other points (each a C{LatLon}).

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

289 C{B{wrap}=False}, if C{True}, wrap or I{normalize} the B{C{points}}

290 (C{bool}).

291

292 @return: A L{Circum4Tuple}C{(radius, center, rank, residuals)} with C{center} an

293 instance of this (sub-)class.

294

295 @raise ImportError: Package C{numpy} not found, not installed or older than

296 version 1.10.

297

298 @raise NumPyError: Some C{numpy} issue.

299

300 @raise TypeError: One of the B{C{points}} invalid.

301

302 @raise ValueError: Too few B{C{points}}.

303

304 @see: Function L{pygeodesy.circum4_} and L{circum3}.

305 '''

306 w, n = self._wrap_name2(**wrap_name)

307

308 def _cs(ps, C, w):

309 _wp = _Wrap.point if w else _passarg

310 for i, p in enumerate(ps):

311 yield C(i=i, points=_wp(p))

312

313 C = self._toCartesianEcef

314 c = C(point=self)

315 t = _MODS.vector2d.circum4_(c, Vector=c.classof, *_cs(points, C, w))

316 c = t.center.toLatLon(LatLon=self.classof)

317 return t.dup(center=c, name=n)

318

319 @property

320 def clipid(self):

321 '''Get the (polygonal) clip (C{int}).

322 '''

323 return self._clipid

324

325 @clipid.setter # PYCHOK setter!

326 def clipid(self, clipid):

327 '''Get the (polygonal) clip (C{int}).

328 '''

329 self._clipid = int(clipid)

330

331 @deprecated_method

332 def compassAngle(self, other, **adjust_wrap): # PYCHOK no cover

333 '''DEPRECATED, use method L{compassAngleTo}.'''

334 return self.compassAngleTo(other, **adjust_wrap)

335

336 def compassAngleTo(self, other, **adjust_wrap):

337 '''Return the angle from North for the direction vector between

338 this and an other point.

339

340 Suitable only for short, non-near-polar vectors up to a few

341 hundred Km or Miles. Use method C{initialBearingTo} for

342 larger distances.

343

344 @arg other: The other point (C{LatLon}).

345 @kwarg adjust_wrap: Optional keyword arguments for function

346 L{pygeodesy.compassAngle}.

347

348 @return: Compass angle from North (C{degrees360}).

349

350 @raise TypeError: The B{C{other}} point is not C{LatLon}.

351

352 @note: Courtesy of Martin Schultz.

353

354 @see: U{Local, flat earth approximation

355 <https://www.EdWilliams.org/avform.htm#flat>}.

356 '''

357 p = self.others(other)

358 return _formy.compassAngle(self.lat, self.lon, p.lat, p.lon, **adjust_wrap)

359

360 @deprecated_method

361 def cosineAndoyerLambertTo(self, other, **wrap):

362 '''DEPRECATED on 2024.12.31, use method L{cosineLawTo} with C{B{corr}=1}.'''

363 return self.cosineLawTo(other, corr=1, **wrap)

364

365 @deprecated_method

366 def cosineForsytheAndoyerLambertTo(self, other, **wrap):

367 '''DEPRECATED on 2024.12.31, use method L{cosineLawTo} with C{B{corr}=2}.'''

368 return self.cosineLawTo(other, corr=2, **wrap)

369

370 def cosineLawTo(self, other, **radius__corr_wrap):

371 '''Compute the distance between this and an other point using the U{Law of

372 Cosines<https://www.Movable-Type.co.UK/scripts/latlong.html#cosine-law>}

373 formula, optionally corrected.

374

375 @arg other: The other point (C{LatLon}).

376 @kwarg radius__corr_wrap: Optional earth C{B{radius}=None} (C{meter}),

377 overriding the equatorial or mean radius of this point's

378 datum's ellipsoid and keyword arguments for function

379 L{pygeodesy.cosineLaw}.

380

381 @return: Distance (C{meter}, same units as B{C{radius}}).

382

383 @raise TypeError: The B{C{other}} point is not C{LatLon}.

384

385 @see: Function L{pygeodesy.cosineLaw} and methods C{distanceTo*},

386 L{equirectangularTo}, L{euclideanTo}, L{flatLocalTo} /

387 L{hubenyTo}, L{flatPolarTo}, L{haversineTo}, L{thomasTo} and

388 L{vincentysTo}.

389 '''

390 c = _xkwds_get(radius__corr_wrap, corr=0)

391 return self._distanceTo_(_formy.cosineLaw_, other, **radius__corr_wrap) if c else \

392 self._distanceTo( _formy.cosineLaw, other, **radius__corr_wrap)

393

394 @property_RO

395 def datum(self): # PYCHOK no cover

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

397 self._notOverloaded()

398

399 def destinationXyz(self, delta, LatLon=None, **LatLon_kwds):

400 '''Calculate the destination using a I{local} delta from this point.

401

402 @arg delta: Local delta to the destination (L{XyzLocal}, L{Aer}, L{Enu}, L{Ned}

403 or L{Local9Tuple}).

404 @kwarg LatLon: Optional (geodetic) class to return the destination or C{None}.

405 @kwarg LatLon_kwds: Optionally, additional B{C{LatLon}} keyword arguments,

406 ignored if C{B{LatLon} is None}.

407

408 @return: An B{C{LatLon}} instance or if C{B{LatLon} is None}, a

409 L{LatLon4Tuple}C{(lat, lon, height, datum)} or L{LatLon3Tuple}C{(lat,

410 lon, height)} if a C{datum} keyword is specified or not.

411

412 @raise TypeError: Invalid B{C{delta}}, B{C{LatLon}} or B{C{LatLon_kwds}} item.

413 '''

414 t = self._ltp._local2ecef(delta, nine=True) # _EcefLocal._ltp

415 return t.toLatLon(LatLon=LatLon, **_xkwds(LatLon_kwds, name=self.name))

416

417 def _distanceTo(self, func, other, radius=None, **kwds):

418 '''(INTERNAL) Helper for distance methods C{<func>To}.

419 '''

420 p = self.others(other, up=2)

421 R = radius or (self._datum.ellipsoid.R1 if self._datum else R_M)

422 return func(self.lat, self.lon, p.lat, p.lon, radius=R, **kwds)

423

424 def _distanceTo_(self, func_, other, wrap=False, radius=None, **kwds):

425 '''(INTERNAL) Helper for (ellipsoidal) distance methods C{<func>To}.

426 '''

427 p = self.others(other, up=2)

428 D = self.datum or _spherical_datum(radius or R_M, func_)

429 lam21, phi2, _ = _Wrap.philam3(self.lam, p.phi, p.lam, wrap)

430 r = func_(phi2, self.phi, lam21, datum=D, **kwds)

431 return r * (radius or D.ellipsoid.a)

432

433 @Property_RO

434 def _Ecef_forward(self):

435 '''(INTERNAL) Helper for L{_ecef9} and L{toEcef} (C{callable}).

436 '''

437 return self.Ecef(self.datum, name=self.name).forward

438

439 @Property_RO

440 def _ecef9(self):

441 '''(INTERNAL) Helper for L{toCartesian}, L{toEcef} and L{toCartesian} (L{Ecef9Tuple}).

442 '''

443 return self._Ecef_forward(self, M=True)

444

445 @property_RO

446 def ellipsoidalLatLon(self):

447 '''Get the C{LatLon type} iff ellipsoidal, overloaded in L{LatLonEllipsoidalBase}.

448 '''

449 return False

450

451 @deprecated_method

452 def equals(self, other, eps=None): # PYCHOK no cover

453 '''DEPRECATED, use method L{isequalTo}.'''

454 return self.isequalTo(other, eps=eps)

455

456 @deprecated_method

457 def equals3(self, other, eps=None): # PYCHOK no cover

458 '''DEPRECATED, use method L{isequalTo3}.'''

459 return self.isequalTo3(other, eps=eps)

460

461 def equirectangularTo(self, other, **radius_adjust_limit_wrap):

462 '''Compute the distance between this and an other point

463 using the U{Equirectangular Approximation / Projection

464 <https://www.Movable-Type.co.UK/scripts/latlong.html#equirectangular>}.

465

466 Suitable only for short, non-near-polar distances up to a

467 few hundred Km or Miles. Use method L{haversineTo} or

468 C{distanceTo*} for more accurate and/or larger distances.

469

470 @arg other: The other point (C{LatLon}).

471 @kwarg radius_adjust_limit_wrap: Optional keyword arguments

472 for function L{pygeodesy.equirectangular},

473 overriding the default mean C{radius} of this

474 point's datum ellipsoid.

475

476 @return: Distance (C{meter}, same units as B{C{radius}}).

477

478 @raise TypeError: The B{C{other}} point is not C{LatLon}.

479

480 @see: Function L{pygeodesy.equirectangular} and methods L{cosineLawTo},

481 C{distanceTo*}, C{euclideanTo}, L{flatLocalTo} / L{hubenyTo},

482 L{flatPolarTo}, L{haversineTo}, L{thomasTo} and L{vincentysTo}.

483 '''

484 return self._distanceTo(_formy.equirectangular, other, **radius_adjust_limit_wrap)

485

486 def euclideanTo(self, other, **radius_adjust_wrap):

487 '''Approximate the C{Euclidian} distance between this and

488 an other point.

489

490 See function L{pygeodesy.euclidean} for the available B{C{options}}.

491

492 @arg other: The other point (C{LatLon}).

493 @kwarg radius_adjust_wrap: Optional keyword arguments for function

494 L{pygeodesy.euclidean}, overriding the default mean

495 C{radius} of this point's datum ellipsoid.

496

497 @return: Distance (C{meter}, same units as B{C{radius}}).

498

499 @raise TypeError: The B{C{other}} point is not C{LatLon}.

500

501 @see: Function L{pygeodesy.euclidean} and methods L{cosineLawTo}, C{distanceTo*},

502 L{equirectangularTo}, L{flatLocalTo} / L{hubenyTo}, L{flatPolarTo},

503 L{haversineTo}, L{thomasTo} and L{vincentysTo}.

504 '''

505 return self._distanceTo(_formy.euclidean, other, **radius_adjust_wrap)

506

507 def flatLocalTo(self, other, radius=None, **wrap):

508 '''Compute the distance between this and an other point using the

509 U{ellipsoidal Earth to plane projection

510 <https://WikiPedia.org/wiki/Geographical_distance#Ellipsoidal_Earth_projected_to_a_plane>}

511 aka U{Hubeny<https://www.OVG.AT/de/vgi/files/pdf/3781/>} formula.

512

513 @arg other: The other point (C{LatLon}).

514 @kwarg radius: Mean earth radius (C{meter}) or C{None} for the I{equatorial

515 radius} of this point's datum ellipsoid.

516 @kwarg wrap: Optional keyword argument C{B{wrap}=False}, if C{True}, wrap

517 or I{normalize} and unroll the B{C{other}} point (C{bool}).

518

519 @return: Distance (C{meter}, same units as B{C{radius}}).

520

521 @raise TypeError: The B{C{other}} point is not C{LatLon}.

522

523 @raise ValueError: Invalid B{C{radius}}.

524

525 @see: Function L{pygeodesy.flatLocal}/L{pygeodesy.hubeny}, methods L{cosineLawTo},

526 C{distanceTo*}, L{equirectangularTo}, L{euclideanTo}, L{flatPolarTo},

527 L{haversineTo}, L{thomasTo} and L{vincentysTo} and U{local, flat Earth

528 approximation<https://www.edwilliams.org/avform.htm#flat>}.

529 '''

530 r = radius if _isin(radius, None, R_M, _1_0, 1) else Radius(radius)

531 return self._distanceTo_(_formy.flatLocal_, other, radius=r, **wrap) # PYCHOK kwargs

532

533 hubenyTo = flatLocalTo # for Karl Hubeny

534

535 def flatPolarTo(self, other, **radius_wrap):

536 '''Compute the distance between this and an other point using

537 the U{polar coordinate flat-Earth<https://WikiPedia.org/wiki/

538 Geographical_distance#Polar_coordinate_flat-Earth_formula>} formula.

539

540 @arg other: The other point (C{LatLon}).

541 @kwarg radius_wrap: Optional C{B{radius}=R_M} and C{B{wrap}=False} for

542 function L{pygeodesy.flatPolar}, overriding the default

543 C{mean radius} of this point's datum ellipsoid.

544

545 @return: Distance (C{meter}, same units as B{C{radius}}).

546

547 @raise TypeError: The B{C{other}} point is not C{LatLon}.

548

549 @see: Function L{pygeodesy.flatPolar} and methods L{cosineLawTo}, C{distanceTo*},

550 L{equirectangularTo}, L{euclideanTo}, L{flatLocalTo} / L{hubenyTo},

551 L{haversineTo}, L{thomasTo} and L{vincentysTo}.

552 '''

553 return self._distanceTo(_formy.flatPolar, other, **radius_wrap)

554

555 def hartzell(self, los=False, earth=None):

556 '''Compute the intersection of a Line-Of-Sight from this (geodetic) Point-Of-View

557 (pov) with this point's ellipsoid surface.

558

559 @kwarg los: Line-Of-Sight, I{direction} to the ellipsoid (L{Los}, L{Vector3d}),

560 C{True} for the I{normal, plumb} onto the surface or I{False} or

561 C{None} to point to the center of the ellipsoid.

562 @kwarg earth: The earth model (L{Datum}, L{Ellipsoid}, L{Ellipsoid2}, L{a_f2Tuple}

563 or C{scalar} radius in C{meter}), overriding this point's C{datum}

564 ellipsoid.

565

566 @return: The intersection (C{LatLon}) with attribute C{.height} set to the distance

567 to this C{pov}.

568

569 @raise IntersectionError: Null or bad C{pov} or B{C{los}}, this C{pov} is inside

570 the ellipsoid or B{C{los}} points outside or away from

571 the ellipsoid.

572

573 @raise TypeError: Invalid B{C{los}} or invalid or undefined B{C{earth}} or C{datum}.

574

575 @see: Function L{hartzell<pygeodesy.formy.hartzell>} for further details.

576 '''

577 return _formy._hartzell(self, los, earth, LatLon=self.classof)

578

579 def haversineTo(self, other, **radius_wrap):

580 '''Compute the distance between this and an other point using the U{Haversine

581 <https://www.Movable-Type.co.UK/scripts/latlong.html>} formula.

582

583 @arg other: The other point (C{LatLon}).

584 @kwarg radius_wrap: Optional C{B{radius}=R_M} and C{B{wrap}=False} for function

585 L{pygeodesy.haversine}, overriding the default C{mean radius} of

586 this point's datum ellipsoid.

587

588 @return: Distance (C{meter}, same units as B{C{radius}}).

589

590 @raise TypeError: The B{C{other}} point is not C{LatLon}.

591

592 @see: Function L{pygeodesy.haversine} and methods L{cosineLawTo}, C{distanceTo*},

593 L{equirectangularTo}, L{euclideanTo}, L{flatLocalTo} / L{hubenyTo}, \

594 L{flatPolarTo}, L{thomasTo} and L{vincentysTo}.

595 '''

596 return self._distanceTo(_formy.haversine, other, **radius_wrap)

597

598 def _havg(self, other, f=_0_5, h=None):

599 '''(INTERNAL) Weighted, average height.

600

601 @arg other: An other point (C{LatLon}).

602 @kwarg f: Optional fraction (C{float}).

603 @kwarg h: Overriding height (C{meter}).

604

605 @return: Average, fractional height (C{float}) or the

606 overriding height B{C{h}} (C{Height}).

607 '''

608 return Height(h) if h is not None else \

609 _MODS.fmath.favg(self.height, other.height, f=f)

610

611 @Property

612 def height(self):

613 '''Get the height (C{meter}).

614 '''

615 return self._height

616

617 @height.setter # PYCHOK setter!

618 def height(self, height):

619 '''Set the height (C{meter}).

620

621 @raise TypeError: Invalid B{C{height}} C{type}.

622

623 @raise ValueError: Invalid B{C{height}}.

624 '''

625 h = Height(height)

626 if self._height != h:

627 _update_all(self)

628 self._height = h

629

630 def _heigHt(self, height):

631 '''(INTERNAL) Overriding this C{height}.

632 '''

633 return self.height if height is None else Height(height)

634

635 def height4(self, earth=None, normal=True, LatLon=None, **LatLon_kwds):

636 '''Compute the projection of this point on and the height above or below

637 this datum's ellipsoid surface.

638

639 @kwarg earth: A datum, ellipsoid, triaxial ellipsoid or earth radius,

640 I{overriding} this datum (L{Datum}, L{Ellipsoid},

641 L{Ellipsoid2}, L{a_f2Tuple}, L{Triaxial}, L{Triaxial_},

642 L{JacobiConformal} or C{meter}, conventionally).

643 @kwarg normal: If C{True}, the projection is the normal to this ellipsoid's

644 surface, otherwise the intersection of the I{radial} line to

645 this ellipsoid's center (C{bool}).

646 @kwarg LatLon: Optional class to return the projection, height and datum

647 (C{LatLon}) or C{None}.

648 @kwarg LatLon_kwds: Optionally, additional B{C{LatLon}} keyword arguments,

649 ignored if C{B{LatLon} is None}.

650

651 @note: Use keyword argument C{height=0} to override C{B{LatLon}.height}

652 to {0} or any other C{scalar}, conventionally in C{meter}.

653

654 @return: A B{C{LatLon}} instance or if C{B{LatLon} is None}, a L{Vector4Tuple}C{(x,

655 y, z, h)} with the I{projection} C{x}, C{y} and C{z} coordinates and

656 height C{h} in C{meter}, conventionally.

657

658 @raise TriaxialError: No convergence in triaxial root finding.

659

660 @raise TypeError: Invalid B{C{LatLon}}, B{C{LatLon_kwds}} item, B{C{earth}}

661 or triaxial B{C{earth}} couldn't be converted to biaxial

662 B{C{LatLon}} datum.

663

664 @see: Methods L{Ellipsoid.height4} and L{Triaxial_.height4} for more information.

665 '''

666 c = self.toCartesian()

667 if LatLon is None:

668 r = c.height4(earth=earth, normal=normal)

669 else:

670 c = c.height4(earth=earth, normal=normal, Cartesian=c.classof, height=0)

671 r = c.toLatLon(LatLon=LatLon, **_xkwds(LatLon_kwds, datum=c.datum, height=c.height))

672 if r.datum != c.datum:

673 raise _TypeError(earth=earth, datum=r.datum)

674 return r

675

676 def heightStr(self, prec=-2, m=_m_):

677 '''Return this point's B{C{height}} as C{str}ing.

678

679 @kwarg prec: Number of (decimal) digits, unstripped (C{int}).

680 @kwarg m: Optional unit of the height (C{str}).

681

682 @see: Function L{pygeodesy.hstr}.

683 '''

684 return _MODS.streprs.hstr(self.height, prec=prec, m=m)

685

686 def intersecant2(self, *args, **kwds): # PYCHOK no cover

687 '''B{Not implemented}, throws a C{NotImplementedError} always.'''

688 self._notImplemented(*args, **kwds)

689

690 def _intersecend2(self, p, q, wrap, height, g_or_r, P, Q, unused): # in .LatLonEllipsoidalBaseDI.intersecant2

691 '''(INTERNAL) Interpolate 2 heights along a geodesic or rhumb

692 line and return the 2 intersecant points accordingly.

693 '''

694 if height is None:

695 hp = hq = _xattr(p, height=INT0)

696 h = _xattr(q, height=hp) # if isLatLon(q) else hp

697 if h != hp:

698 s = g_or_r._Inverse(p, q, wrap).s12

699 if s: # fmath.fidw?

700 s = (h - hp) / s # slope

701 hq += s * Q.s12

702 hp += s * P.s12

703 else:

704 hp = hq = _MODS.fmath.favg(hp, h)

705 else:

706 hp = hq = Height(height)

707

708# n = self.name or typename(unused)

709 p = q = self.classof(P.lat2, P.lon2, datum=g_or_r.datum, height=hp) # name=n

710 p._iteration = P.iteration

711 if P is not Q:

712 q = self.classof(Q.lat2, Q.lon2, datum=g_or_r.datum, height=hq) # name=n

713 q._iteration = Q.iteration

714 return p, q

715

716 @deprecated_method

717 def isantipode(self, other, eps=EPS): # PYCHOK no cover

718 '''DEPRECATED, use method L{isantipodeTo}.'''

719 return self.isantipodeTo(other, eps=eps)

720

721 def isantipodeTo(self, other, eps=EPS):

722 '''Check whether this and an other point are antipodal, on diametrically

723 opposite sides of the earth.

724

725 @arg other: The other point (C{LatLon}).

726 @kwarg eps: Tolerance for near-equality (C{degrees}).

727

728 @return: C{True} if points are antipodal within the given tolerance,

729 C{False} otherwise.

730 '''

731 p = self.others(other)

732 return _formy.isantipode(*(self.latlon + p.latlon), eps=eps)

733

734 @Property_RO

735 def isEllipsoidal(self):

736 '''Check whether this point is ellipsoidal (C{bool} or C{None} if unknown).

737 '''

738 return _xattr(self.datum, isEllipsoidal=None)

739

740 def isequalTo(self, other, eps=None):

741 '''Compare this point with an other point, I{ignoring} height.

742

743 @arg other: The other point (C{LatLon}).

744 @kwarg eps: Tolerance for equality (C{degrees}).

745

746 @return: C{True} if both points are identical, I{ignoring} height,

747 C{False} otherwise.

748

749 @raise TypeError: The B{C{other}} point is not C{LatLon} or mismatch

750 of the B{C{other}} and this C{class} or C{type}.

751

752 @raise UnitError: Invalid B{C{eps}}.

753

754 @see: Method L{isequalTo3}.

755 '''

756 return _formy._isequalTo(self, self.others(other), eps=eps)

757

758 def isequalTo3(self, other, eps=None):

759 '''Compare this point with an other point, I{including} height.

760

761 @arg other: The other point (C{LatLon}).

762 @kwarg eps: Tolerance for equality (C{degrees}).

763

764 @return: C{True} if both points are identical I{including} height,

765 C{False} otherwise.

766

767 @raise TypeError: The B{C{other}} point is not C{LatLon} or mismatch

768 of the B{C{other}} and this C{class} or C{type}.

769

770 @see: Method L{isequalTo}.

771 '''

772 return self.height == self.others(other).height and \

773 _formy._isequalTo(self, other, eps=eps)

774

775 @Property_RO

776 def isnormal(self):

777 '''Return C{True} if this point is normal (C{bool}),

778 meaning C{abs(lat) <= 90} and C{abs(lon) <= 180}.

779

780 @see: Methods L{normal}, L{toNormal} and functions L{isnormal

781 <pygeodesy.isnormal>} and L{normal<pygeodesy.normal>}.

782 '''

783 return _formy.isnormal(self.lat, self.lon, eps=0)

784

785 @Property_RO

786 def isSpherical(self):

787 '''Check whether this point is spherical (C{bool} or C{None} if unknown).

788 '''

789 return _xattr(self.datum, isSpherical=None)

790

791 @Property_RO

792 def lam(self):

793 '''Get the longitude (B{C{radians}}).

794 '''

795 return radians(self.lon)

796

797 @Property

798 def lat(self):

799 '''Get the latitude (C{degrees90}).

800 '''

801 return self._lat

802

803 @lat.setter # PYCHOK setter!

804 def lat(self, lat):

805 '''Set the latitude (C{str[N|S]} or C{degrees}).

806

807 @raise ValueError: Invalid B{C{lat}}.

808 '''

809 lat = Lat(lat) # parseDMS(lat, suffix=_NS_, clip=90)

810 if self._lat != lat:

811 _update_all(self)

812 self._lat = lat

813

814 @Property

815 def latlon(self):

816 '''Get the lat- and longitude (L{LatLon2Tuple}C{(lat, lon)}).

817 '''

818 return LatLon2Tuple(self._lat, self._lon, name=self.name)

819

820 @latlon.setter # PYCHOK setter!

821 def latlon(self, latlonh):

822 '''Set the lat- and longitude and optionally the height (2- or 3-tuple

823 or comma- or space-separated C{str} of C{degrees90}, C{degrees180}

824 and C{meter}).

825

826 @raise TypeError: Height of B{C{latlonh}} not C{scalar} or B{C{latlonh}}

827 not C{list} or C{tuple}.

828

829 @raise ValueError: Invalid B{C{latlonh}} or M{len(latlonh)}.

830

831 @see: Function L{pygeodesy.parse3llh} to parse a B{C{latlonh}} string

832 into a 3-tuple C{(lat, lon, h)}.

833 '''

834 if isstr(latlonh):

835 latlonh = parse3llh(latlonh, height=self.height)

836 else:

837 _xinstanceof(list, tuple, latlonh=latlonh)

838 if len(latlonh) == 3:

839 h = Height(latlonh[2], name=Fmt.SQUARE(latlonh=2))

840 elif len(latlonh) != 2:

841 raise _ValueError(latlonh=latlonh)

842 else:

843 h = self.height

844

845 llh = Lat(latlonh[0]), Lon(latlonh[1]), h # parseDMS2(latlonh[0], latlonh[1])

846 if (self._lat, self._lon, self._height) != llh:

847 _update_all(self)

848 self._lat, self._lon, self._height = llh

849

850 def latlon2(self, ndigits=0):

851 '''Return this point's lat- and longitude in C{degrees}, rounded.

852

853 @kwarg ndigits: Number of (decimal) digits (C{int}).

854

855 @return: A L{LatLon2Tuple}C{(lat, lon)}, both C{float} and rounded

856 away from zero.

857

858 @note: The C{round}ed values are always C{float}, also if B{C{ndigits}}

859 is omitted.

860 '''

861 return LatLon2Tuple(round(self.lat, ndigits),

862 round(self.lon, ndigits), name=self.name)

863

864 @deprecated_method

865 def latlon_(self, ndigits=0): # PYCHOK no cover

866 '''DEPRECATED, use method L{latlon2}.'''

867 return self.latlon2(ndigits=ndigits)

868

869 latlon2round = latlon_ # PYCHOK no cover

870

871 @Property

872 def latlonheight(self):

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

874 '''

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

876

877 @latlonheight.setter # PYCHOK setter!

878 def latlonheight(self, latlonh):

879 '''Set the lat- and longitude and optionally the height

880 (2- or 3-tuple or comma- or space-separated C{str} of

881 C{degrees90}, C{degrees180} and C{meter}).

882

883 @see: Property L{latlon} for more details.

884 '''

885 self.latlon = latlonh

886

887 @Property

888 def lon(self):

889 '''Get the longitude (C{degrees180}).

890 '''

891 return self._lon

892

893 @lon.setter # PYCHOK setter!

894 def lon(self, lon):

895 '''Set the longitude (C{str[E|W]} or C{degrees}).

896

897 @raise ValueError: Invalid B{C{lon}}.

898 '''

899 lon = Lon(lon) # parseDMS(lon, suffix=_EW_, clip=180)

900 if self._lon != lon:

901 _update_all(self)

902 self._lon = lon

903

904# _ltp = _EcefLocal._ltp(self)

905

906 def nearestOn6(self, points, closed=False, height=None, wrap=False):

907 '''Locate the point on a path or polygon closest to this point.

908

909 Points are converted to and distances are computed in I{geocentric},

910 cartesian space.

911

912 @arg points: The path or polygon points (C{LatLon}[]).

913 @kwarg closed: Optionally, close the polygon (C{bool}).

914 @kwarg height: Optional height, overriding the height of this and all

915 other points (C{meter}). If C{None}, take the height

916 of points into account for distances.

917 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the B{C{points}}

918 (C{bool}).

919

920 @return: A L{NearestOn6Tuple}C{(closest, distance, fi, j, start, end)}

921 with the C{closest}, the C{start} and the C{end} point each an

922 instance of this C{LatLon} and C{distance} in C{meter}, same

923 units as the cartesian axes.

924

925 @raise PointsError: Insufficient number of B{C{points}}.

926

927 @raise TypeError: Some B{C{points}} or some B{C{points}}' C{Ecef} invalid.

928

929 @raise ValueError: Some B{C{points}}' C{Ecef} is incompatible.

930

931 @see: Function L{nearestOn6<pygeodesy.nearestOn6>}.

932 '''

933 def _cs(Ps, h, w, C):

934 p = None # not used

935 for i, q in Ps.enumerate():

936 if w and i:

937 q = _unrollon(p, q)

938 yield C(height=h, i=i, up=3, points=q)

939 p = q

940

941 C = self._toCartesianEcef # to verify datum and Ecef

942 Ps = self.PointsIter(points, wrap=wrap)

943

944 c = C(height=height, this=self) # this Cartesian

945 t = _MODS.vector3d.nearestOn6(c, _cs(Ps, height, wrap, C), closed=closed)

946 c, s, e = t.closest, t.start, t.end

947

948 kwds = _xkwds_not(None, LatLon=self.classof, # this LatLon

949 height=height)

950 _r = self.Ecef(self.datum).reverse

951 p = _r(c).toLatLon(**kwds)

952 s = _r(s).toLatLon(**kwds) if s is not c else p

953 e = _r(e).toLatLon(**kwds) if e is not c else p

954 return t.dup(closest=p, start=s, end=e)

955

956 def nearestTo(self, *args, **kwds): # PYCHOK no cover

957 '''B{Not implemented}, throws a C{NotImplementedError} always.'''

958 self._notImplemented(*args, **kwds)

959

960 def normal(self):

961 '''Normalize this point I{in-place} to C{abs(lat) <= 90} and C{abs(lon) <= 180}.

962

963 @return: C{True} if this point was I{normal}, C{False} if it wasn't (but is now).

964

965 @see: Property L{isnormal} and method L{toNormal}.

966 '''

967 n = self.isnormal

968 if not n:

969 self.latlon = _formy.normal(*self.latlon)

970 return n

971

972 @property_RO

973 def _N_vector(self):

974 '''(INTERNAL) Get the C{Nvector} (C{nvectorBase._N_Vector})

975 '''

976 _N = _MODS.nvectorBase._N_Vector

977 return _N(*self._n_xyz3, h=self.height, name=self.name)

978

979 @Property_RO

980 def _n_xyz3(self):

981 '''(INTERNAL) Get the n-vector components as L{Vector3Tuple}.

982 '''

983 return philam2n_xyz(self.phi, self.lam, name=self.name)

984

985 @Property_RO

986 def phi(self):

987 '''Get the latitude (B{C{radians}}).

988 '''

989 return radians(self.lat)

990

991 @Property_RO

992 def philam(self):

993 '''Get the lat- and longitude (L{PhiLam2Tuple}C{(phi, lam)}).

994 '''

995 return PhiLam2Tuple(self.phi, self.lam, name=self.name)

996

997 def philam2(self, ndigits=0):

998 '''Return this point's lat- and longitude in C{radians}, rounded.

999

1000 @kwarg ndigits: Number of (decimal) digits (C{int}).

1001

1002 @return: A L{PhiLam2Tuple}C{(phi, lam)}, both C{float} and rounded

1003 away from zero.

1004

1005 @note: The C{round}ed values are C{float}, always.

1006 '''

1007 return PhiLam2Tuple(round(self.phi, ndigits),

1008 round(self.lam, ndigits), name=self.name)

1009

1010 @Property_RO

1011 def philamheight(self):

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

1013 '''

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

1015

1016 @deprecated_method

1017 def points(self, points, **closed): # PYCHOK no cover

1018 '''DEPRECATED, use method L{points2}.'''

1019 return self.points2(points, **closed)

1020

1021 def points2(self, points, closed=True):

1022 '''Check a path or polygon represented by points.

1023

1024 @arg points: The path or polygon points (C{LatLon}[])

1025 @kwarg closed: Optionally, consider the polygon closed, ignoring any

1026 duplicate or closing final B{C{points}} (C{bool}).

1027

1028 @return: A L{Points2Tuple}C{(number, points)}, an C{int} and a C{list}

1029 or C{tuple}.

1030

1031 @raise PointsError: Insufficient number of B{C{points}}.

1032

1033 @raise TypeError: Some B{C{points}} are not C{LatLon}.

1034 '''

1035 return _MODS.iters.points2(points, closed=closed, base=self)

1036

1037 def PointsIter(self, points, loop=0, dedup=False, wrap=False):

1038 '''Return a C{PointsIter} iterator.

1039

1040 @arg points: The path or polygon points (C{LatLon}[])

1041 @kwarg loop: Number of loop-back points (non-negative C{int}).

1042 @kwarg dedup: If C{True}, skip duplicate points (C{bool}).

1043 @kwarg wrap: If C{True}, wrap or I{normalize} the enum-/iterated

1044 B{C{points}} (C{bool}).

1045

1046 @return: A new C{PointsIter} iterator.

1047

1048 @raise PointsError: Insufficient number of B{C{points}}.

1049 '''

1050 return _MODS.iters.PointsIter(points, base=self, loop=loop,

1051 dedup=dedup, wrap=wrap)

1052

1053 def radii11(self, point2, point3, wrap=False):

1054 '''Return the radii of the C{Circum-}, C{In-}, I{Soddy} and C{Tangent}

1055 circles of a (planar) triangle formed by this and two other points.

1056

1057 @arg point2: Second point (C{LatLon}).

1058 @arg point3: Third point (C{LatLon}).

1059 @kwarg wrap: If C{True}, wrap or I{normalize} B{C{point2}} and

1060 B{C{point3}} (C{bool}).

1061

1062 @return: L{Radii11Tuple}C{(rA, rB, rC, cR, rIn, riS, roS, a, b, c, s)}.

1063

1064 @raise IntersectionError: Near-coincident or -colinear points.

1065

1066 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}.

1067

1068 @see: Function L{pygeodesy.radii11}, U{Incircle

1069 <https://MathWorld.Wolfram.com/Incircle.html>}, U{Soddy Circles

1070 <https://MathWorld.Wolfram.com/SoddyCircles.html>} and U{Tangent

1071 Circles<https://MathWorld.Wolfram.com/TangentCircles.html>}.

1072 '''

1073 with _toCartesian3(self, point2, point3, wrap) as cs:

1074 return _MODS.vector2d._radii11ABC4(*cs, useZ=True)[0]

1075

1076 def _rhumb3(self, exact, radius): # != .sphericalBase._rhumbs3

1077 '''(INTERNAL) Get the C{rhumb} for this point's datum or for

1078 the B{C{radius}}' earth model iff non-C{None}.

1079 '''

1080 try:

1081 d = self._rhumb3dict

1082 t = d[(exact, radius)]

1083 except KeyError:

1084 D = self.datum if radius is None else \

1085 _spherical_datum(radius) # ellipsoidal OK

1086 try:

1087 r = D.ellipsoid.rhumb_(exact=exact) # or D.isSpherical

1088 except AttributeError as x:

1089 raise _AttributeError(datum=D, radius=radius, cause=x)

1090 t = r, D, _MODS.karney.Caps

1091 if len(d) > 2:

1092 d.clear() # d[:] = {}

1093 d[(exact, radius)] = t # cache 3-tuple

1094 return t

1095

1096 @Property_RO

1097 def _rhumb3dict(self): # in ._update

1098 return {} # 3-item cache

1099

1100 def rhumbAzimuthTo(self, other, exact=False, radius=None, wrap=False, b360=False):

1101 '''Return the azimuth (bearing) of a rhumb line (loxodrome) between this and

1102 an other (ellipsoidal) point.

1103

1104 @arg other: The other point (C{LatLon}).

1105 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method

1106 L{Ellipsoid.rhumb_}.

1107 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},

1108 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's datum.

1109 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the B{C{other}} point (C{bool}).

1110 @kwarg b360: If C{True}, return the azimuth as bearing in compass degrees (C{bool}).

1111

1112 @return: Rhumb azimuth (C{degrees180} or compass C{degrees360}).

1113

1114 @raise TypeError: The B{C{other}} point is incompatible or B{C{radius}} is invalid.

1115 '''

1116 r, _, Cs = self._rhumb3(exact, radius)

1117 z = r._Inverse(self, other, wrap, outmask=Cs.AZIMUTH).azi12

1118 return _umod_360(z + _360_0) if b360 else z

1119

1120 def rhumbDestination(self, distance, azimuth, radius=None, height=None, exact=False, **name):

1121 '''Return the destination point having travelled the given distance from this point along

1122 a rhumb line (loxodrome) of the given azimuth.

1123

1124 @arg distance: Distance travelled (C{meter}, same units as this point's datum (ellipsoid)

1125 axes or B{C{radius}}, may be negative.

1126 @arg azimuth: Azimuth (bearing) of the rhumb line (compass C{degrees}).

1127 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},

1128 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's datum.

1129 @kwarg height: Optional height, overriding the default height (C{meter}).

1130 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method L{Ellipsoid.rhumb_}.

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

1132

1133 @return: The destination point (ellipsoidal C{LatLon}).

1134

1135 @raise TypeError: Invalid B{C{radius}}.

1136

1137 @raise ValueError: Invalid B{C{distance}}, B{C{azimuth}}, B{C{radius}} or B{C{height}}.

1138 '''

1139 r, D, _ = self._rhumb3(exact, radius)

1140 d = r._Direct(self, azimuth, distance)

1141 h = self._heigHt(height)

1142 return self.classof(d.lat2, d.lon2, datum=D, height=h, **name)

1143

1144 def rhumbDistanceTo(self, other, exact=False, radius=None, wrap=False):

1145 '''Return the distance from this to an other point along a rhumb line (loxodrome).

1146

1147 @arg other: The other point (C{LatLon}).

1148 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method L{Ellipsoid.rhumb_}.

1149 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},

1150 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's datum.

1151 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the B{C{other}} point (C{bool}).

1152

1153 @return: Distance (C{meter}, the same units as this point's datum (ellipsoid) axes or B{C{radius}}.

1154

1155 @raise TypeError: The B{C{other}} point is incompatible or B{C{radius}} is invalid.

1156

1157 @raise ValueError: Invalid B{C{radius}}.

1158 '''

1159 r, _, Cs = self._rhumb3(exact, radius)

1160 return r._Inverse(self, other, wrap, outmask=Cs.DISTANCE).s12

1161

1162 def rhumbIntersecant2(self, circle, point, other, height=None,

1163 **exact_radius_wrap_eps_tol):

1164 '''Compute the intersections of a circle and a rhumb line given as two points or as a

1165 point and azimuth.

1166

1167 @arg circle: Radius of the circle centered at this location (C{meter}), or a point

1168 on the circle (same C{LatLon} class).

1169 @arg point: The start point of the rhumb line (same C{LatLon} class).

1170 @arg other: An other point I{on} (same C{LatLon} class) or the azimuth I{of} (compass

1171 C{degrees}) the rhumb line.

1172 @kwarg height: Optional height for the intersection points (C{meter}, conventionally)

1173 or C{None} for interpolated heights.

1174 @kwarg exact_radius_wrap_eps_tol: Optional keyword arguments, see methods L{rhumbLine}

1175 and L{RhumbLineAux.Intersecant2} or L{RhumbLine.Intersecant2}.

1176

1177 @return: 2-Tuple of the intersection points (representing a chord), each an instance of

1178 this class. Both points are the same instance if the rhumb line is tangent to

1179 the circle.

1180

1181 @raise IntersectionError: The circle and rhumb line do not intersect.

1182

1183 @raise TypeError: Invalid B{C{point}}, B{C{circle}} or B{C{other}}.

1184

1185 @raise ValueError: Invalid B{C{circle}}, B{C{other}}, B{C{height}} or B{C{exact_radius_wrap}}.

1186

1187 @see: Methods L{RhumbLineAux.Intersecant2} and L{RhumbLine.Intersecant2}.

1188 '''

1189 def _kwds3(eps=EPS, tol=_TOL, wrap=False, **kwds):

1190 return kwds, wrap, dict(eps=eps, tol=tol)

1191

1192 exact_radius, w, eps_tol = _kwds3(**exact_radius_wrap_eps_tol)

1193

1194 p = _unrollon(self, self.others(point=point), wrap=w)

1195 try:

1196 r = Radius_(circle=circle) if _isRadius(circle) else \

1197 self.rhumbDistanceTo(self.others(circle=circle), wrap=w, **exact_radius)

1198 rl = p.rhumbLine(other, wrap=w, **exact_radius)

1199 P, Q = rl.Intersecant2(self.lat, self.lon, r, **eps_tol)

1200

1201 return self._intersecend2(p, other, w, height, rl.rhumb, P, Q,

1202 self.rhumbIntersecant2)

1203 except (TypeError, ValueError) as x:

1204 raise _xError(x, center=self, circle=circle, point=point, other=other,

1205 **exact_radius_wrap_eps_tol)

1206

1207 def rhumbLine(self, other, exact=False, radius=None, wrap=False, **name_caps):

1208 '''Get a rhumb line through this point at a given azimuth or through this and an other point.

1209

1210 @arg other: The azimuth I{of} (compass C{degrees}) or an other point I{on} (same

1211 C{LatLon} class) the rhumb line.

1212 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method L{Ellipsoid.rhumb_}.

1213 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},

1214 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's C{datum}.

1215 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the B{C{other}} point (C{bool}).

1216 @kwarg name_caps: Optional C{B{name}=str} and C{caps}, see L{RhumbLine} or L{RhumbLineAux} C{B{caps}}.

1217

1218 @return: A C{RhumbLine} instance (C{RhumbLine} or C{RhumbLineAux}).

1219

1220 @raise TypeError: Invalid B{C{radius}} or B{C{other}} not C{scalar} nor same C{LatLon} class.

1221

1222 @see: Modules L{rhumb.aux_} and L{rhumb.ekx}.

1223 '''

1224 r, _, Cs = self._rhumb3(exact, radius)

1225 kwds = _xkwds(name_caps, name=self.name, caps=Cs.LINE_OFF)

1226 rl = r._DirectLine( self, other, **kwds) if _isDegrees(other) else \

1227 r._InverseLine(self, self.others(other), wrap, **kwds)

1228 return rl

1229

1230 def rhumbMidpointTo(self, other, exact=False, radius=None, height=None, fraction=_0_5, **wrap_name):

1231 '''Return the (loxodromic) midpoint on the rhumb line between this and an other point.

1232

1233 @arg other: The other point (same C{LatLon} class).

1234 @kwarg exact: Exact C{Rhumb...} to use (C{bool} or C{Rhumb...}), see method L{Ellipsoid.rhumb_}.

1235 @kwarg radius: Optional earth radius (C{meter}) or earth model (L{Datum}, L{Ellipsoid},

1236 L{Ellipsoid2} or L{a_f2Tuple}), overriding this point's datum.

1237 @kwarg height: Optional height, overriding the mean height (C{meter}).

1238 @kwarg fraction: Midpoint location from this point (C{scalar}), 0 for this, 1 for the B{C{other}},

1239 0.5 for halfway between this and the B{C{other}} point, may be negative or

1240 greater than 1.

1241 @kwarg wrap_name: Optional C{B{name}=NN} (C{str}) and C{B{wrap}=False}, if C{True}, wrap or

1242 I{normalize} and unroll the B{C{other}} point (C{bool}).

1243

1244 @return: The midpoint at the given B{C{fraction}} along the rhumb line (same C{LatLon} class).

1245

1246 @raise TypeError: The B{C{other}} point is incompatible or B{C{radius}} is invalid.

1247

1248 @raise ValueError: Invalid B{C{height}} or B{C{fraction}}.

1249 '''

1250 w, n = self._wrap_name2(**wrap_name)

1251 r, D, _ = self._rhumb3(exact, radius)

1252 f = Scalar(fraction=fraction)

1253 d = r._Inverse(self, self.others(other), w) # C.AZIMUTH_DISTANCE

1254 d = r._Direct( self, d.azi12, d.s12 * f)

1255 h = self._havg(other, f=f, h=height)

1256 return self.classof(d.lat2, d.lon2, datum=D, height=h, name=n)

1257

1258 @property_RO

1259 def sphericalLatLon(self):

1260 '''Get the C{LatLon type} iff spherical, overloaded in L{LatLonSphericalBase}.

1261 '''

1262 return False

1263

1264 def thomasTo(self, other, **wrap):

1265 '''Compute the distance between this and an other point using U{Thomas'

1266 <https://apps.DTIC.mil/dtic/tr/fulltext/u2/703541.pdf>} formula.

1267

1268 @arg other: The other point (C{LatLon}).

1269 @kwarg wrap: Optional keyword argument C{B{wrap}=False}, if C{True}, wrap

1270 or I{normalize} and unroll the B{C{other}} point (C{bool}).

1271

1272 @return: Distance (C{meter}, same units as the axes of this point's datum ellipsoid).

1273

1274 @raise TypeError: The B{C{other}} point is not C{LatLon}.

1275

1276 @see: Function L{pygeodesy.thomas} and methods L{cosineLawTo}, C{distanceTo*},

1277 L{equirectangularTo}, L{euclideanTo}, L{flatLocalTo} / L{hubenyTo},

1278 L{flatPolarTo}, L{haversineTo} and L{vincentysTo}.

1279 '''

1280 return self._distanceTo_(_formy.thomas_, other, **wrap)

1281

1282 @deprecated_method

1283 def to2ab(self): # PYCHOK no cover

1284 '''DEPRECATED, use property L{philam}.'''

1285 return self.philam

1286

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

1288 '''Convert this point to cartesian, I{geocentric} coordinates, also known as

1289 I{Earth-Centered, Earth-Fixed} (ECEF).

1290

1291 @kwarg height: Optional height, overriding this point's height (C{meter},

1292 conventionally).

1293 @kwarg Cartesian: Optional class to return the geocentric coordinates

1294 (C{Cartesian}) or C{None}.

1295 @kwarg Cartesian_kwds: Optionally, additional B{C{Cartesian}} keyword

1296 arguments, ignored if C{B{Cartesian} is None}.

1297

1298 @return: A B{C{Cartesian}} instance or if B{C{Cartesian} is None}, an

1299 L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, datum)} with

1300 C{C=0} and C{M} if available.

1301

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

1303

1304 @see: Methods C{toNvector}, C{toVector} and C{toVector3d}.

1305 '''

1306 r = self._ecef9 if height is None else self.toEcef(height=height)

1307 if Cartesian is not None: # class or .classof

1308 r = Cartesian(r, **self._name1__(Cartesian_kwds))

1309 _xdatum(r.datum, self.datum)

1310 return r

1311

1312 def _toCartesianEcef(self, height=None, i=None, up=2, **name_point):

1313 '''(INTERNAL) Convert to cartesian and check Ecef's before and after.

1314 '''

1315 p = self.others(up=up, **name_point)

1316 c = p.toCartesian(height=height)

1317 E = self.Ecef

1318 if E:

1319 for p in (p, c):

1320 e = _xattr(p, Ecef=None)

1321 if not _isin(e, None, E): # PYCHOK no cover

1322 n, _ = _xkwds_item2(name_point)

1323 n = Fmt.INDEX(n, i)

1324 t = _incompatible(typename(E))

1325 raise _ValueError(n, e, txt=t) # txt__

1326 return c

1327

1328 def toDatum(self, datum2, height=None, **name):

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

1330 self._notOverloaded(datum2, height=height, **name)

1331

1332 def toEcef(self, height=None, M=False):

1333 '''Convert this point to I{geocentric} coordinates, also known as

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

1335

1336 @kwarg height: Optional height, overriding this point's height (C{meter},

1337 conventionally).

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

1339

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

1341 C{C=0} and C{M} if available.

1342

1343 @raise EcefError: A C{.datum} or an ECEF issue.

1344 '''

1345 return self._ecef9 if _isin(height, None, self.height) else \

1346 self._Ecef_forward(self.lat, self.lon, height=height, M=M)

1347

1348 @deprecated_method

1349 def to3llh(self, height=None): # PYCHOK no cover

1350 '''DEPRECATED, use property L{latlonheight} or C{latlon.to3Tuple(B{height})}.'''

1351 return self.latlonheight if _isin(height, None, self.height) else \

1352 self.latlon.to3Tuple(height)

1353

1354 def toNormal(self, deep=False, **name):

1355 '''Get this point I{normalized} to C{abs(lat) <= 90} and C{abs(lon) <= 180}.

1356

1357 @kwarg deep: If C{True}, make a deep, otherwise a shallow copy (C{bool}).

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

1359

1360 @return: A copy of this point, I{normalized} (C{LatLon}), optionally renamed.

1361

1362 @see: Property L{isnormal}, method L{normal} and function L{pygeodesy.normal}.

1363 '''

1364 ll = self.copy(deep=deep)

1365 _ = ll.normal()

1366 if name:

1367 ll.rename(name)

1368 return ll

1369

1370 def toNvector(self, h=None, Nvector=None, **name_Nvector_kwds):

1371 '''Convert this point to C{n-vector} (normal to the earth's surface) components,

1372 I{including height}.

1373

1374 @kwarg h: Optional height, overriding this point's height (C{meter}).

1375 @kwarg Nvector: Optional class to return the C{n-vector} components (C{Nvector})

1376 or C{None}.

1377 @kwarg name_Nvector_kwds: Optional C{B{name}=NN} (C{str}) and optionally,

1378 additional B{C{Nvector}} keyword arguments, ignored if C{B{Nvector}

1379 is None}.

1380

1381 @return: An B{C{Nvector}} instance or a L{Vector4Tuple}C{(x, y, z, h)} if

1382 C{B{Nvector} is None}.

1383

1384 @raise TypeError: Invalid B{C{h}}, B{C{Nvector}} or B{C{name_Nvector_kwds}}.

1385

1386 @see: Methods C{toCartesian}, C{toVector} and C{toVector3d}.

1387 '''

1388 h = self._heigHt(h)

1389 if Nvector is None:

1390 r = self._n_xyz3.to4Tuple(h)

1391 n, _ = _name2__(name_Nvector_kwds, _or_nameof=self)

1392 if n:

1393 r.rename(n)

1394 else:

1395 x, y, z = self._n_xyz3

1396 r = Nvector(x, y, z, h=h, ll=self, **self._name1__(name_Nvector_kwds))

1397 return r

1398

1399 def toStr(self, form=F_DMS, joined=_COMMASPACE_, m=_m_, **prec_sep_s_D_M_S): # PYCHOK expected

1400 '''Convert this point to a "lat, lon[, +/-height]" string, formatted in the

1401 given C{B{form}at}.

1402

1403 @kwarg form: The lat-/longitude C{B{form}at} to use (C{str}), see functions

1404 L{pygeodesy.latDMS} or L{pygeodesy.lonDMS}.

1405 @kwarg joined: Separator to join the lat-, longitude and height strings (C{str}

1406 or C{None} or C{NN} for non-joined).

1407 @kwarg m: Optional unit of the height (C{str}), use C{None} to exclude height

1408 from the returned string.

1409 @kwarg prec_sep_s_D_M_S: Optional C{B{prec}ision}, C{B{sep}arator}, B{C{s_D}},

1410 B{C{s_M}}, B{C{s_S}} and B{C{s_DMS}} keyword arguments, see function

1411 L{pygeodesy.toDMS} for details.

1412

1413 @return: This point in the specified C{B{form}at}, etc. (C{str} or a 2- or 3-tuple

1414 C{(lat_str, lon_str[, height_str])} if B{C{joined}} is C{NN} or C{None}).

1415

1416 @see: Function L{pygeodesy.latDMS} or L{pygeodesy.lonDMS} for more details about

1417 keyword arguments C{B{form}at}, C{B{prec}ision}, C{B{sep}arator}, B{C{s_D}},

1418 B{C{s_M}}, B{C{s_S}} and B{C{s_DMS}}.

1419 '''

1420 t = (latDMS(self.lat, form=form, **prec_sep_s_D_M_S),

1421 lonDMS(self.lon, form=form, **prec_sep_s_D_M_S))

1422 if self.height and m is not None:

1423 t += (self.heightStr(m=m),)

1424 return joined.join(t) if joined else t

1425

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

1427 '''Convert this point to a C{Vector} with the I{geocentric} C{(x, y, z)} (ECEF)

1428 coordinates, I{ignoring height}.

1429

1430 @kwarg Vector: Optional class to return the I{geocentric} components (L{Vector3d})

1431 or C{None}.

1432 @kwarg Vector_kwds: Optionally, additional B{C{Vector}} keyword arguments,

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

1434

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

1436 is None}.

1437

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

1439

1440 @see: Methods C{toCartesian}, C{toNvector} and C{toVector3d}.

1441 '''

1442 return self._ecef9.toVector(Vector=Vector, **self._name1__(Vector_kwds))

1443

1444 def toVector3d(self, norm=True, **Vector3d_kwds):

1445 '''Convert this point to a L{Vector3d} with the I{geocentric} C{(x, y, z)}

1446 (ECEF) coordinates, I{ignoring height}.

1447

1448 @kwarg norm: If C{False}, don't normalize the coordinates (C{bool}).

1449 @kwarg Vector3d_kwds: Optional L{Vector3d} keyword arguments.

1450

1451 @return: Named, unit vector or vector (L{Vector3d}).

1452

1453 @raise TypeError: Invalid B{C{Vector3d_kwds}}.

1454

1455 @see: Methods C{toCartesian}, C{toNvector} and C{toVector}.

1456 '''

1457 r = self.toVector(Vector=_MODS.vector3d.Vector3d, **Vector3d_kwds)

1458 if norm:

1459 r = r.unit(ll=self)

1460 return r

1461

1462 def toWm(self, **toWm_kwds):

1463 '''Convert this point to a WM coordinate.

1464

1465 @kwarg toWm_kwds: Optional L{pygeodesy.toWm} keyword arguments.

1466

1467 @return: The WM coordinate (L{Wm}).

1468

1469 @see: Function L{pygeodesy.toWm}.

1470 '''

1471 return _MODS.webmercator.toWm(self, **self._name1__(toWm_kwds))

1472

1473 @deprecated_method

1474 def to3xyz(self): # PYCHOK no cover

1475 '''DEPRECATED, use property L{xyz} or method L{toNvector}, L{toVector},

1476 L{toVector3d} or perhaps (geocentric) L{toEcef}.'''

1477 return self.xyz # self.toVector()

1478

1479# def _update(self, updated, *attrs, **setters):

1480# '''(INTERNAL) See C{_NamedBase._update}.

1481# '''

1482# if updated:

1483# self._rhumb3dict.clear()

1484# return _NamedBase._update(self, updated, *attrs, **setters)

1485

1486 def vincentysTo(self, other, **radius_wrap):

1487 '''Compute the distance between this and an other point using U{Vincenty's

1488 <https://WikiPedia.org/wiki/Great-circle_distance>} spherical formula.

1489

1490 @arg other: The other point (C{LatLon}).

1491 @kwarg radius_wrap: Optional C{B{radius}=R_M} and C{B{wrap}=False} for

1492 function L{pygeodesy.vincentys}, overriding the default

1493 C{mean radius} of this point's datum ellipsoid.

1494

1495 @return: Distance (C{meter}, same units as B{C{radius}}).

1496

1497 @raise TypeError: The B{C{other}} point is not C{LatLon}.

1498

1499 @see: Function L{pygeodesy.vincentys} and methods L{cosineLawTo}, C{distanceTo*},

1500 L{equirectangularTo}, L{euclideanTo}, L{flatLocalTo} / L{hubenyTo},

1501 L{flatPolarTo}, L{haversineTo} and L{thomasTo}.

1502 '''

1503 return self._distanceTo(_formy.vincentys, other, **_xkwds(radius_wrap, radius=None))

1504

1505 def _wrap_name2(self, wrap=False, **name):

1506 '''(INTERNAL) Return the C{wrap} and C{name} value.

1507 '''

1508 return wrap, (self._name__(name) if name else NN)

1509

1510 @property_RO

1511 def xyz(self):

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

1513 '''

1514 return self._ecef9.xyz

1515

1516 @property_RO

1517 def xyz3(self):

1518 '''Get the I{geocentric} C{(x, y, z)} coordinates as C{3-tuple}.

1519 '''

1520 return tuple(self.xyz)

1521

1522 @Property_RO

1523 def xyzh(self):

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

1525 '''

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

1527

1528

1529 class _toCartesian3(object): # see also .formy._idllmn6, .geodesicw._wargs, .vector2d._numpy

1530 '''(INTERNAL) Wrapper to convert 2 other points.

1531 '''

1532 @contextmanager # <https://www.Python.org/dev/peps/pep-0343/> Examples

1533 def __call__(self, p, p2, p3, wrap, **kwds):

1534 try:

1535 if wrap:

1536 p2, p3 = map1(_Wrap.point, p2, p3)

1537 kwds = _xkwds(kwds, wrap=wrap)

1538 yield (p. toCartesian().copy(name=_point_), # copy to rename

1539 p._toCartesianEcef(up=4, point2=p2),

1540 p._toCartesianEcef(up=4, point3=p3))

1541 except (AssertionError, TypeError, ValueError) as x: # Exception?

1542 raise _xError(x, point=p, point2=p2, point3=p3, **kwds)

1543

1544 _toCartesian3 = _toCartesian3() # PYCHOK singleton

1545

1546

1547 def _latlonheight3(latlonh, height, wrap): # in .points.LatLon_.__init__

1548 '''(INTERNAL) Get 3-tuple C{(lat, lon, height)}.

1549 '''

1550 try:

1551 lat, lon = latlonh.lat, latlonh.lon

1552 height = _xattr(latlonh, height=height)

1553 except AttributeError:

1554 raise _IsnotError(_LatLon_, latlonh=latlonh)

1555 if wrap:

1556 lat, lon = _Wrap.latlon(lat, lon)

1557 return lat, lon, height

1558

1559

1560 def latlon2n_xyz(lat_ll, lon=None, **name):

1561 '''Convert lat-, longitude to C{n-vector} (I{normal} to the earth's surface) X, Y and Z components.

1562

1563 @arg lat_ll: Latitude (C{degrees}) or a C{LatLon} instance, L{LatLon2Tuple} or other C{LatLon*Tuple}.

1564 @kwarg lon: Longitude (C{degrees}), required if C{B{lon_ll} is degrees}, ignored otherwise.

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

1566

1567 @return: A L{Vector3Tuple}C{(x, y, z)}.

1568

1569 @see: Function L{philam2n_xyz}.

1570

1571 @note: These are C{n-vector} x, y and z components, I{NOT geocentric} x, y and z (ECEF) coordinates!

1572 '''

1573 lat = lat_ll

1574 if lon is None:

1575 try:

1576 lat, lon = lat_ll.latlon

1577 except AttributeError:

1578 lat = lat_ll.lat

1579 lon = lat_ll.lon

1580 # Kenneth Gade eqn 3, but using right-handed

1581 # vector x -> 0°E,0°N, y -> 90°E,0°N, z -> 90°N

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

1583 return Vector3Tuple(ca * cb, ca * sb, sa, **name)

1584

1585

1586 def philam2n_xyz(phi_ll, lam=None, **name):

1587 '''Convert lat-, longitude to C{n-vector} (I{normal} to the earth's surface) X, Y and Z components.

1588

1589 @arg phi_ll: Latitude (C{radians}) or a C{LatLon} instance with C{phi}, C{lam} or C{philam} attributes.

1590 @kwarg lam: Longitude (C{radians}), required if C{B{phi_ll} is radians}, ignored otherwise.

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

1592

1593 @return: A L{Vector3Tuple}C{(x, y, z)}.

1594

1595 @see: Function L{latlon2n_xyz}.

1596

1597 @note: These are C{n-vector} x, y and z components, I{NOT geocentric} x, y and z (ECEF) coordinates!

1598 '''

1599 phi = phi_ll

1600 if lam is None:

1601 try:

1602 phi, lam = phi_ll.philam

1603 except AttributeError:

1604 phi = phi_ll.phi

1605 lam = phi_ll.lam

1606 return latlon2n_xyz(degrees(phi), degrees(lam), **name)

1607

1608

1609 def _trilaterate5(p1, d1, p2, d2, p3, d3, area=True, eps=EPS1, radius=R_M, wrap=False): # MCCABE 13

1610 '''(INTERNAL) Trilaterate three points by I{area overlap} or by I{perimeter intersection} of three circles.

1611

1612 @note: The B{C{radius}} is needed only for C{n-vectorial} and C{sphericalTrigonometry.LatLon.distanceTo}

1613 methods and silently ignored by the C{ellipsoidalExact}, C{-GeodSolve}, C{-Karney} and

1614 C{-Vincenty.LatLon.distanceTo} methods.

1615 '''

1616 p2, p3, w = _unrollon3(p1, p2, p3, wrap)

1617 rw = dict(radius=radius, wrap=w)

1618

1619 r1 = Distance_(distance1=d1)

1620 r2 = Distance_(distance2=d2)

1621 r3 = Distance_(distance3=d3)

1622 m = 0 if area else (r1 + r2 + r3)

1623 pc = 0

1624 t = []

1625 for _ in range(3):

1626 try: # intersection of circle (p1, r1) and (p2, r2)

1627 c1, c2 = p1.intersections2(r1, p2, r2, wrap=w)

1628

1629 if area: # check overlap

1630 if c1 is c2: # abutting

1631 c = c1

1632 else: # nearest point on radical

1633 c = p3.nearestOn(c1, c2, within=True, wrap=w)

1634 d = r3 - p3.distanceTo(c, **rw)

1635 if d > eps: # sufficient overlap

1636 t.append((d, c))

1637 m = max(m, d)

1638

1639 else: # check intersection

1640 for c in ((c1,) if c1 is c2 else (c1, c2)):

1641 d = fabs(r3 - p3.distanceTo(c, **rw))

1642 if d < eps: # below margin

1643 t.append((d, c))

1644 m = min(m, d)

1645

1646 except IntersectionError as x:

1647 if _concentric_ in str(x): # XXX ConcentricError?

1648 pc += 1

1649

1650 p1, r1, p2, r2, p3, r3 = p2, r2, p3, r3, p1, r1 # rotate

1651

1652 if t: # get min, max, points and count ...

1653 t = tuple(sorted(t))

1654 n = len(t), # as 1-tuple

1655 # ... or for a single trilaterated result,

1656 # min *is* max, min- *is* maxPoint and n=1, 2 or 3

1657 return Trilaterate5Tuple(t[0] + t[-1] + n) # *(t[0] + ...)

1658

1659 elif area and pc == 3: # all pairwise concentric ...

1660 r, p = min((r1, p1), (r2, p2), (r3, p3))

1661 m = max(r1, r2, r3)

1662 # ... return "smallest" point twice, the smallest

1663 # and largest distance and n=0 for concentric

1664 return Trilaterate5Tuple(float(r), p, float(m), p, 0)

1665

1666 n, f = (_overlap_, max) if area else (_intersection_, min)

1667 t = _COMMASPACE_(_no_(n), '%s %.3g' % (typename(f), m))

1668 raise IntersectionError(area=area, eps=eps, wrap=wrap, txt=t)

1669

1670

1671 __all__ += _ALL_DOCS(LatLonBase)

1672

1673# **) MIT License

1674#

1675# Copyright (C) 2016-2026 -- mrJean1 at Gmail -- All Rights Reserved.

1676#

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

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

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

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

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

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

1683#

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

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

1686#

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

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

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

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

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

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

1693# OTHER DEALINGS IN THE SOFTWARE.