1

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

3

4 u'''Formulary of basic geodesy functions and approximations.

5'''

6# make sure int/int division yields float quotient, see .basics

7 from __future__ import division as _; del _ # PYCHOK semicolon

8

9# from pygeodesy.cartesianBase import CartesianBase # _MODS

10 from pygeodesy.constants import EPS, EPS0, EPS1, PI, PI2, PI3, PI_2, R_M, \

11 _0_0s, float0_, isnon0, remainder, _umod_PI2, \

12 _0_0, _0_125, _0_25, _0_5, _1_0, _2_0, _4_0, \

13 _32_0, _90_0, _180_0, _360_0

14 from pygeodesy.datums import Datum, Ellipsoid, _ellipsoidal_datum, \

15 _mean_radius, _spherical_datum, _WGS84, _EWGS84

16# from pygeodesy.ellipsoids import Ellipsoid, _EWGS84 # from .datums

17 from pygeodesy.errors import IntersectionError, LimitError, limiterrors, \

18 _TypeError, _ValueError, _xattr, _xError, \

19 _xcallable,_xkwds, _xkwds_pop2

20 from pygeodesy.fmath import euclid, hypot, hypot2, sqrt0

21 from pygeodesy.fsums import fsumf_, Fmt, unstr

22# from pygeodesy.internals import _dunder_nameof # from .named

23 from pygeodesy.interns import _delta_, _distant_, _inside_, _SPACE_, _too_

24 from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS

25 from pygeodesy.named import _name__, _name2__, _NamedTuple, _xnamed, \

26 _dunder_nameof

27 from pygeodesy.namedTuples import Bearing2Tuple, Distance4Tuple, LatLon2Tuple, \

28 Intersection3Tuple, PhiLam2Tuple, Vector3Tuple

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

30# from pygeodesy.triaxials import _hartzell3 # _MODS

31 from pygeodesy.units import _isHeight, _isRadius, Bearing, Degrees_, Distance, \

32 Distance_, Height, Lam_, Lat, Lon, Meter_, Phi_, \

33 Radians, Radians_, Radius, Radius_, Scalar, _100km

34 from pygeodesy.utily import acos1, atan2b, atan2d, degrees2m, _loneg, m2degrees, \

35 tan_2, sincos2, sincos2_, sincos2d_, _Wrap

36# from pygeodesy.vector3d import _otherV3d # _MODS

37# from pygeodesy.vector3dBase import _xyz_y_z3 # _MODS

38# from pygeodesy import ellipsoidalExact, ellipsoidalKarney, vector3d, \

39# sphericalNvector, sphericalTrigonometry # _MODS

40

41 from contextlib import contextmanager

42 from math import asin, atan, atan2, cos, degrees, fabs, radians, sin, sqrt # pow

43

44__all__ = _ALL_LAZY.formy

45__version__ = '24.05.28'

46

47_RADIANS2 = (PI / _180_0)**2 # degrees- to radians-squared

48_ratio_ = 'ratio'

49_xline_ = 'xline'

50

51

52 def _anti2(a, b, n_2, n, n2):

53 '''(INTERNAL) Helper for C{antipode} and C{antipode_}.

54 '''

55 r = remainder(a, n) if fabs(a) > n_2 else a

56 if r == a:

57 r = -r

58 b += n

59 if fabs(b) > n:

60 b = remainder(b, n2)

61 return float0_(r, b)

62

63

64 def antipode(lat, lon, **name):

65 '''Return the antipode, the point diametrically opposite

66 to a given point in C{degrees}.

67

68 @arg lat: Latitude (C{degrees}).

69 @arg lon: Longitude (C{degrees}).

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

71

72 @return: A L{LatLon2Tuple}C{(lat, lon)}.

73

74 @see: Functions L{antipode_} and L{normal} and U{Geosphere

75 <https://CRAN.R-Project.org/web/packages/geosphere/geosphere.pdf>}.

76 '''

77 return LatLon2Tuple(*_anti2(lat, lon, _90_0, _180_0, _360_0), **name)

78

79

80 def antipode_(phi, lam, **name):

81 '''Return the antipode, the point diametrically opposite

82 to a given point in C{radians}.

83

84 @arg phi: Latitude (C{radians}).

85 @arg lam: Longitude (C{radians}).

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

87

88 @return: A L{PhiLam2Tuple}C{(phi, lam)}.

89

90 @see: Functions L{antipode} and L{normal_} and U{Geosphere

91 <https://CRAN.R-Project.org/web/packages/geosphere/geosphere.pdf>}.

92 '''

93 return PhiLam2Tuple(*_anti2(phi, lam, PI_2, PI, PI2), **name)

94

95

96 def bearing(lat1, lon1, lat2, lon2, **final_wrap):

97 '''Compute the initial or final bearing (forward or reverse

98 azimuth) between a (spherical) start and end point.

99

100 @arg lat1: Start latitude (C{degrees}).

101 @arg lon1: Start longitude (C{degrees}).

102 @arg lat2: End latitude (C{degrees}).

103 @arg lon2: End longitude (C{degrees}).

104 @kwarg final_wrap: Optional keyword arguments for function

105 L{pygeodesy.bearing_}.

106

107 @return: Initial or final bearing (compass C{degrees360}) or

108 zero if start and end point coincide.

109 '''

110 r = bearing_(Phi_(lat1=lat1), Lam_(lon1=lon1),

111 Phi_(lat2=lat2), Lam_(lon2=lon2), **final_wrap)

112 return degrees(r)

113

114

115 def bearing_(phi1, lam1, phi2, lam2, final=False, wrap=False):

116 '''Compute the initial or final bearing (forward or reverse azimuth)

117 between a (spherical) start and end point.

118

119 @arg phi1: Start latitude (C{radians}).

120 @arg lam1: Start longitude (C{radians}).

121 @arg phi2: End latitude (C{radians}).

122 @arg lam2: End longitude (C{radians}).

123 @kwarg final: If C{True}, return the final, otherwise the initial

124 bearing (C{bool}).

125 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll B{C{phi2}}

126 and B{C{lam2}} (C{bool}).

127

128 @return: Initial or final bearing (compass C{radiansPI2}) or zero if

129 start and end point coincide.

130

131 @see: U{Bearing<https://www.Movable-Type.co.UK/scripts/latlong.html>},

132 U{Course between two points<https://www.EdWilliams.org/avform147.htm#Crs>}

133 and U{Bearing Between Two Points<https://web.Archive.org/web/20020630205931/

134 https://MathForum.org/library/drmath/view/55417.html>}.

135 '''

136 db, phi2, lam2 = _Wrap.philam3(lam1, phi2, lam2, wrap)

137 if final: # swap plus PI

138 phi1, lam1, phi2, lam2, db = phi2, lam2, phi1, lam1, -db

139 r = PI3

140 else:

141 r = PI2

142 sa1, ca1, sa2, ca2, sdb, cdb = sincos2_(phi1, phi2, db)

143

144 x = ca1 * sa2 - sa1 * ca2 * cdb

145 y = sdb * ca2

146 return _umod_PI2(atan2(y, x) + r) # .utily.wrapPI2

147

148

149 def _bearingTo2(p1, p2, wrap=False): # for points.ispolar, sphericalTrigonometry.areaOf

150 '''(INTERNAL) Compute initial and final bearing.

151 '''

152 try: # for LatLon_ and ellipsoidal LatLon

153 return p1.bearingTo2(p2, wrap=wrap)

154 except AttributeError:

155 pass

156 # XXX spherical version, OK for ellipsoidal ispolar?

157 t = p1.philam + p2.philam

158 return Bearing2Tuple(degrees(bearing_(*t, final=False, wrap=wrap)),

159 degrees(bearing_(*t, final=True, wrap=wrap)),

160 name__=_bearingTo2)

161

162

163 def compassAngle(lat1, lon1, lat2, lon2, adjust=True, wrap=False):

164 '''Return the angle from North for the direction vector M{(lon2 - lon1,

165 lat2 - lat1)} between two points.

166

167 Suitable only for short, not near-polar vectors up to a few hundred

168 Km or Miles. Use function L{pygeodesy.bearing} for longer vectors.

169

170 @arg lat1: From latitude (C{degrees}).

171 @arg lon1: From longitude (C{degrees}).

172 @arg lat2: To latitude (C{degrees}).

173 @arg lon2: To longitude (C{degrees}).

174 @kwarg adjust: Adjust the longitudinal delta by the cosine of the

175 mean latitude (C{bool}).

176 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll B{C{lat2}}

177 and B{C{lon2}} (C{bool}).

178

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

180

181 @note: Courtesy of Martin Schultz.

182

183 @see: U{Local, flat earth approximation

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

185 '''

186 d_lon, lat2, lon2 = _Wrap.latlon3(lon1, lat2, lon2, wrap)

187 if adjust: # scale delta lon

188 d_lon *= _scale_deg(lat1, lat2)

189 return atan2b(d_lon, lat2 - lat1)

190

191

192 def cosineAndoyerLambert(lat1, lon1, lat2, lon2, datum=_WGS84, wrap=False):

193 '''Compute the distance between two (ellipsoidal) points using the U{Andoyer-Lambert

194 <https://books.google.com/books?id=x2UiAQAAIAAJ>} correction of the U{Law of

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

196

197 @arg lat1: Start latitude (C{degrees}).

198 @arg lon1: Start longitude (C{degrees}).

199 @arg lat2: End latitude (C{degrees}).

200 @arg lon2: End longitude (C{degrees}).

201 @kwarg datum: Datum (L{Datum}) or ellipsoid (L{Ellipsoid},

202 L{Ellipsoid2} or L{a_f2Tuple}) to use.

203 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll

204 B{C{lat2}} and B{C{lon2}} (C{bool}).

205

206 @return: Distance (C{meter}, same units as the B{C{datum}}'s

207 ellipsoid axes or C{radians} if B{C{datum}} is C{None}).

208

209 @raise TypeError: Invalid B{C{datum}}.

210

211 @see: Functions L{cosineAndoyerLambert_}, L{cosineForsytheAndoyerLambert},

212 L{cosineLaw}, L{equirectangular}, L{euclidean}, L{flatLocal}/L{hubeny},

213 L{flatPolar}, L{haversine}, L{thomas} and L{vincentys} and method

214 L{Ellipsoid.distance2}.

215 '''

216 return _dE(cosineAndoyerLambert_, datum, wrap, lat1, lon1, lat2, lon2)

217

218

219 def cosineAndoyerLambert_(phi2, phi1, lam21, datum=_WGS84):

220 '''Compute the I{angular} distance between two (ellipsoidal) points using the U{Andoyer-Lambert

221 <https://books.google.com/books?id=x2UiAQAAIAAJ>} correction of the U{Law of

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

223

224 @arg phi2: End latitude (C{radians}).

225 @arg phi1: Start latitude (C{radians}).

226 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).

227 @kwarg datum: Datum (L{Datum}) or ellipsoid (L{Ellipsoid},

228 L{Ellipsoid2} or L{a_f2Tuple}) to use.

229

230 @return: Angular distance (C{radians}).

231

232 @raise TypeError: Invalid B{C{datum}}.

233

234 @see: Functions L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert_},

235 L{cosineLaw_}, L{euclidean_}, L{flatLocal_}/L{hubeny_}, L{flatPolar_},

236 L{haversine_}, L{thomas_} and L{vincentys_} and U{Geodesy-PHP

237 <https://GitHub.com/jtejido/geodesy-php/blob/master/src/Geodesy/Distance/

238 AndoyerLambert.php>}.

239 '''

240 s2, c2, s1, c1, r, c21 = _sincosa6(phi2, phi1, lam21)

241 if isnon0(c1) and isnon0(c2):

242 E = _ellipsoidal(datum, cosineAndoyerLambert_)

243 if E.f: # ellipsoidal

244 r2 = atan2(E.b_a * s2, c2)

245 r1 = atan2(E.b_a * s1, c1)

246 s2, c2, s1, c1 = sincos2_(r2, r1)

247 r = acos1(s1 * s2 + c1 * c2 * c21)

248 if r:

249 sr, _, sr_2, cr_2 = sincos2_(r, r * _0_5)

250 if isnon0(sr_2) and isnon0(cr_2):

251 s = (sr + r) * ((s1 - s2) / sr_2)**2

252 c = (sr - r) * ((s1 + s2) / cr_2)**2

253 r += (c - s) * E.f * _0_125

254 return r

255

256

257 def cosineForsytheAndoyerLambert(lat1, lon1, lat2, lon2, datum=_WGS84, wrap=False):

258 '''Compute the distance between two (ellipsoidal) points using the U{Forsythe-Andoyer-Lambert

259 <https://www2.UNB.Ca/gge/Pubs/TR77.pdf>} correction of the U{Law of Cosines

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

261

262 @arg lat1: Start latitude (C{degrees}).

263 @arg lon1: Start longitude (C{degrees}).

264 @arg lat2: End latitude (C{degrees}).

265 @arg lon2: End longitude (C{degrees}).

266 @kwarg datum: Datum (L{Datum}) or ellipsoid (L{Ellipsoid},

267 L{Ellipsoid2} or L{a_f2Tuple}) to use.

268 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll

269 B{C{lat2}} and B{C{lon2}} (C{bool}).

270

271 @return: Distance (C{meter}, same units as the B{C{datum}}'s

272 ellipsoid axes or C{radians} if B{C{datum}} is C{None}).

273

274 @raise TypeError: Invalid B{C{datum}}.

275

276 @see: Functions L{cosineForsytheAndoyerLambert_}, L{cosineAndoyerLambert},

277 L{cosineLaw}, L{equirectangular}, L{euclidean}, L{flatLocal}/L{hubeny},

278 L{flatPolar}, L{haversine}, L{thomas} and L{vincentys} and method

279 L{Ellipsoid.distance2}.

280 '''

281 return _dE(cosineForsytheAndoyerLambert_, datum, wrap, lat1, lon1, lat2, lon2)

282

283

284 def cosineForsytheAndoyerLambert_(phi2, phi1, lam21, datum=_WGS84):

285 '''Compute the I{angular} distance between two (ellipsoidal) points using the

286 U{Forsythe-Andoyer-Lambert<https://www2.UNB.Ca/gge/Pubs/TR77.pdf>} correction of

287 the U{Law of Cosines<https://www.Movable-Type.co.UK/scripts/latlong.html#cosine-law>}

288 formula.

289

290 @arg phi2: End latitude (C{radians}).

291 @arg phi1: Start latitude (C{radians}).

292 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).

293 @kwarg datum: Datum (L{Datum}) or ellipsoid to use (L{Ellipsoid},

294 L{Ellipsoid2} or L{a_f2Tuple}).

295

296 @return: Angular distance (C{radians}).

297

298 @raise TypeError: Invalid B{C{datum}}.

299

300 @see: Functions L{cosineForsytheAndoyerLambert}, L{cosineAndoyerLambert_},

301 L{cosineLaw_}, L{euclidean_}, L{flatLocal_}/L{hubeny_}, L{flatPolar_},

302 L{haversine_}, L{thomas_} and L{vincentys_} and U{Geodesy-PHP

303 <https://GitHub.com/jtejido/geodesy-php/blob/master/src/Geodesy/

304 Distance/ForsytheCorrection.php>}.

305 '''

306 s2, c2, s1, c1, r, _ = _sincosa6(phi2, phi1, lam21)

307 if r and isnon0(c1) and isnon0(c2):

308 E = _ellipsoidal(datum, cosineForsytheAndoyerLambert_)

309 if E.f: # ellipsoidal

310 sr, cr, s2r, _ = sincos2_(r, r * 2)

311 if isnon0(sr) and fabs(cr) < EPS1:

312 s = (s1 + s2)**2 / (1 + cr)

313 t = (s1 - s2)**2 / (1 - cr)

314 x = s + t

315 y = s - t

316

317 s = 8 * r**2 / sr

318 a = 64 * r + s * cr * 2 # 16 * r**2 / tan(r)

319 d = 48 * sr + s # 8 * r**2 / tan(r)

320 b = -2 * d

321 e = 30 * s2r

322 c = fsumf_(30 * r, e * _0_5, s * cr) # 8 * r**2 / tan(r)

323 t = fsumf_( a * x, e * y**2, b * y, -c * x**2, d * x * y)

324

325 r += fsumf_(-r * x, 3 * y * sr, t * E.f / _32_0) * E.f * _0_25

326 return r

327

328

329 def cosineLaw(lat1, lon1, lat2, lon2, radius=R_M, wrap=False):

330 '''Compute the distance between two points using the U{spherical Law of Cosines

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

332

333 @arg lat1: Start latitude (C{degrees}).

334 @arg lon1: Start longitude (C{degrees}).

335 @arg lat2: End latitude (C{degrees}).

336 @arg lon2: End longitude (C{degrees}).

337 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum})

338 or ellipsoid (L{Ellipsoid}, L{Ellipsoid2} or

339 L{a_f2Tuple}) to use.

340 @kwarg wrap: If C{True}, wrap or I{normalize} and B{C{lat2}}

341 and B{C{lon2}} (C{bool}).

342

343 @return: Distance (C{meter}, same units as B{C{radius}} or the

344 ellipsoid or datum axes).

345

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

347

348 @see: Functions L{cosineLaw_}, L{cosineAndoyerLambert},

349 L{cosineForsytheAndoyerLambert}, L{equirectangular}, L{euclidean},

350 L{flatLocal}/L{hubeny}, L{flatPolar}, L{haversine}, L{thomas} and

351 L{vincentys} and method L{Ellipsoid.distance2}.

352

353 @note: See note at function L{vincentys_}.

354 '''

355 return _dS(cosineLaw_, radius, wrap, lat1, lon1, lat2, lon2)

356

357

358 def cosineLaw_(phi2, phi1, lam21):

359 '''Compute the I{angular} distance between two points using the U{spherical Law of

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

361

362 @arg phi2: End latitude (C{radians}).

363 @arg phi1: Start latitude (C{radians}).

364 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).

365

366 @return: Angular distance (C{radians}).

367

368 @see: Functions L{cosineLaw}, L{cosineAndoyerLambert_},

369 L{cosineForsytheAndoyerLambert_}, L{euclidean_},

370 L{flatLocal_}/L{hubeny_}, L{flatPolar_}, L{haversine_},

371 L{thomas_} and L{vincentys_}.

372

373 @note: See note at function L{vincentys_}.

374 '''

375 return _sincosa6(phi2, phi1, lam21)[4]

376

377

378 def _d3(wrap, lat1, lon1, lat2, lon2):

379 '''(INTERNAL) Helper for _dE, _dS and _eA.

380 '''

381 if wrap:

382 d_lon, lat2, _ = _Wrap.latlon3(lon1, lat2, lon2, wrap)

383 return radians(lat2), Phi_(lat1=lat1), radians(d_lon)

384 else: # for backward compaibility

385 return Phi_(lat2=lat2), Phi_(lat1=lat1), Phi_(d_lon=lon2 - lon1)

386

387

388 def _dE(func_, earth, *wrap_lls):

389 '''(INTERNAL) Helper for ellipsoidal distances.

390 '''

391 E = _ellipsoidal(earth, func_)

392 r = func_(*_d3(*wrap_lls), datum=E)

393 return r * E.a

394

395

396 def _dS(func_, radius, *wrap_lls, **adjust):

397 '''(INTERNAL) Helper for spherical distances.

398 '''

399 r = func_(*_d3(*wrap_lls), **adjust)

400 if radius is not R_M:

401 _, lat1, _, lat2, _ = wrap_lls

402 radius = _mean_radius(radius, lat1, lat2)

403 return r * radius

404

405

406 def _eA(excess_, radius, *wrap_lls):

407 '''(INTERNAL) Helper for spherical excess or area.

408 '''

409 r = excess_(*_d3(*wrap_lls))

410 if radius:

411 _, lat1, _, lat2, _ = wrap_lls

412 r *= _mean_radius(radius, lat1, lat2)**2

413 return r

414

415

416 def _ellipsoidal(earth, where):

417 '''(INTERNAL) Helper for distances.

418 '''

419 return _EWGS84 if earth in (_WGS84, _EWGS84) else (

420 earth if isinstance(earth, Ellipsoid) else

421 (earth if isinstance(earth, Datum) else # PYCHOK indent

422 _ellipsoidal_datum(earth, name__=where)).ellipsoid)

423

424

425 def equirectangular(lat1, lon1, lat2, lon2, radius=R_M, **adjust_limit_wrap):

426 '''Compute the distance between two points using the U{Equirectangular Approximation

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

428

429 @arg lat1: Start latitude (C{degrees}).

430 @arg lon1: Start longitude (C{degrees}).

431 @arg lat2: End latitude (C{degrees}).

432 @arg lon2: End longitude (C{degrees}).

433 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum}) or ellipsoid

434 (L{Ellipsoid}, L{Ellipsoid2} or L{a_f2Tuple}).

435 @kwarg adjust_limit_wrap: Optional keyword arguments for function L{equirectangular4}.

436

437 @return: Distance (C{meter}, same units as B{C{radius}} or the ellipsoid or datum axes).

438

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

440

441 @see: Function L{equirectangular4} for more details, the available B{C{options}},

442 errors, restrictions and other, approximate or accurate distance functions.

443 '''

444 d = sqrt(equirectangular4(Lat(lat1=lat1), Lon(lon1=lon1),

445 Lat(lat2=lat2), Lon(lon2=lon2),

446 **adjust_limit_wrap).distance2) # PYCHOK 4 vs 2-3

447 return degrees2m(d, radius=_mean_radius(radius, lat1, lat2))

448

449

450 def _equirectangular(lat1, lon1, lat2, lon2, **adjust_limit_wrap):

451 '''(INTERNAL) Helper for the L{frechet._FrechetMeterRadians}

452 and L{hausdorff._HausdorffMeterRedians} classes.

453 '''

454 return equirectangular4(lat1, lon1, lat2, lon2, **adjust_limit_wrap).distance2 * _RADIANS2

455

456

457 def equirectangular4(lat1, lon1, lat2, lon2, adjust=True, limit=45, wrap=False):

458 '''Compute the distance between two points using the U{Equirectangular Approximation

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

460

461 This approximation is valid for short distance of several hundred Km

462 or Miles, see the B{C{limit}} keyword argument and L{LimitError}.

463

464 @arg lat1: Start latitude (C{degrees}).

465 @arg lon1: Start longitude (C{degrees}).

466 @arg lat2: End latitude (C{degrees}).

467 @arg lon2: End longitude (C{degrees}).

468 @kwarg adjust: Adjust the wrapped, unrolled longitudinal delta by the cosine

469 of the mean latitude (C{bool}).

470 @kwarg limit: Optional limit for lat- and longitudinal deltas (C{degrees}) or

471 C{None} or C{0} for unlimited.

472 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll B{C{lat2}} and

473 B{C{lon2}} (C{bool}).

474

475 @return: A L{Distance4Tuple}C{(distance2, delta_lat, delta_lon, unroll_lon2)}

476 in C{degrees squared}.

477

478 @raise LimitError: If the lat- and/or longitudinal delta exceeds the

479 B{C{-limit..limit}} range and L{pygeodesy.limiterrors}

480 set to C{True}.

481

482 @see: U{Local, flat earth approximation

483 <https://www.EdWilliams.org/avform.htm#flat>}, functions

484 L{equirectangular}, L{cosineAndoyerLambert},

485 L{cosineForsytheAndoyerLambert}, L{cosineLaw}, L{euclidean},

486 L{flatLocal}/L{hubeny}, L{flatPolar}, L{haversine}, L{thomas}

487 and L{vincentys} and methods L{Ellipsoid.distance2},

488 C{LatLon.distanceTo*} and C{LatLon.equirectangularTo}.

489 '''

490 d_lon, lat2, ulon2 = _Wrap.latlon3(lon1, lat2, lon2, wrap)

491 d_lat = lat2 - lat1

492

493 if limit and limit > 0 and limiterrors():

494 d = max(fabs(d_lat), fabs(d_lon))

495 if d > limit:

496 t = _SPACE_(_delta_, Fmt.PAREN_g(d), Fmt.exceeds_limit(limit))

497 s = unstr(equirectangular4, lat1, lon1, lat2, lon2,

498 limit=limit, wrap=wrap)

499 raise LimitError(s, txt=t)

500

501 if adjust: # scale delta lon

502 d_lon *= _scale_deg(lat1, lat2)

503

504 d2 = hypot2(d_lat, d_lon) # degrees squared!

505 return Distance4Tuple(d2, d_lat, d_lon, ulon2 - lon2)

506

507

508 def euclidean(lat1, lon1, lat2, lon2, radius=R_M, adjust=True, wrap=False):

509 '''Approximate the C{Euclidean} distance between two (spherical) points.

510

511 @arg lat1: Start latitude (C{degrees}).

512 @arg lon1: Start longitude (C{degrees}).

513 @arg lat2: End latitude (C{degrees}).

514 @arg lon2: End longitude (C{degrees}).

515 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum})

516 or ellipsoid (L{Ellipsoid}, L{Ellipsoid2} or

517 L{a_f2Tuple}) to use.

518 @kwarg adjust: Adjust the longitudinal delta by the cosine of

519 the mean latitude (C{bool}).

520 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll B{C{lat2}}

521 and B{C{lon2}} (C{bool}).

522

523 @return: Distance (C{meter}, same units as B{C{radius}} or the

524 ellipsoid or datum axes).

525

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

527

528 @see: U{Distance between two (spherical) points

529 <https://www.EdWilliams.org/avform.htm#Dist>}, functions L{euclid},

530 L{euclidean_}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

531 L{cosineLaw}, L{equirectangular}, L{flatLocal}/L{hubeny}, L{flatPolar},

532 L{haversine}, L{thomas} and L{vincentys} and methods L{Ellipsoid.distance2},

533 C{LatLon.distanceTo*} and C{LatLon.equirectangularTo}.

534 '''

535 return _dS(euclidean_, radius, wrap, lat1, lon1, lat2, lon2, adjust=adjust)

536

537

538 def euclidean_(phi2, phi1, lam21, adjust=True):

539 '''Approximate the I{angular} C{Euclidean} distance between two (spherical) points.

540

541 @arg phi2: End latitude (C{radians}).

542 @arg phi1: Start latitude (C{radians}).

543 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).

544 @kwarg adjust: Adjust the longitudinal delta by the cosine

545 of the mean latitude (C{bool}).

546

547 @return: Angular distance (C{radians}).

548

549 @see: Functions L{euclid}, L{euclidean}, L{cosineAndoyerLambert_},

550 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

551 L{flatLocal_}/L{hubeny_}, L{flatPolar_}, L{haversine_},

552 L{thomas_} and L{vincentys_}.

553 '''

554 if adjust:

555 lam21 *= _scale_rad(phi2, phi1)

556 return euclid(phi2 - phi1, lam21)

557

558

559 def excessAbc_(A, b, c):

560 '''Compute the I{spherical excess} C{E} of a (spherical) triangle from two sides

561 and the included (small) angle.

562

563 @arg A: An interior triangle angle (C{radians}).

564 @arg b: Frist adjacent triangle side (C{radians}).

565 @arg c: Second adjacent triangle side (C{radians}).

566

567 @return: Spherical excess (C{radians}).

568

569 @raise UnitError: Invalid B{C{A}}, B{C{b}} or B{C{c}}.

570

571 @see: Functions L{excessGirard_}, L{excessLHuilier_} and U{Spherical

572 trigonometry<https://WikiPedia.org/wiki/Spherical_trigonometry>}.

573 '''

574 A = Radians_(A=A)

575 b = Radians_(b=b) * _0_5

576 c = Radians_(c=c) * _0_5

577

578 sA, cA, sb, cb, sc, cc = sincos2_(A, b, c)

579 return atan2(sA * sb * sc, cb * cc + cA * sb * sc) * _2_0

580

581

582 def excessCagnoli_(a, b, c):

583 '''Compute the I{spherical excess} C{E} of a (spherical) triangle using U{Cagnoli's

584 <https://Zenodo.org/record/35392>} (D.34) formula.

585

586 @arg a: First triangle side (C{radians}).

587 @arg b: Second triangle side (C{radians}).

588 @arg c: Third triangle side (C{radians}).

589

590 @return: Spherical excess (C{radians}).

591

592 @raise UnitError: Invalid B{C{a}}, B{C{b}} or B{C{c}}.

593

594 @see: Function L{excessLHuilier_} and U{Spherical trigonometry

595 <https://WikiPedia.org/wiki/Spherical_trigonometry>}.

596 '''

597 a = Radians_(a=a)

598 b = Radians_(b=b)

599 c = Radians_(c=c)

600

601 s = fsumf_(a, b, c) * _0_5

602 _s = sin

603 r = _s(s) * _s(s - a) * _s(s - b) * _s(s - c)

604 c = cos(a * _0_5) * cos(b * _0_5) * cos(c * _0_5)

605 r = asin(sqrt(r) * _0_5 / c) if c and r > 0 else _0_0

606 return Radians(Cagnoli=r * _2_0)

607

608

609 def excessGirard_(A, B, C):

610 '''Compute the I{spherical excess} C{E} of a (spherical) triangle using U{Girard's

611 <https://MathWorld.Wolfram.com/GirardsSphericalExcessFormula.html>} formula.

612

613 @arg A: First interior triangle angle (C{radians}).

614 @arg B: Second interior triangle angle (C{radians}).

615 @arg C: Third interior triangle angle (C{radians}).

616

617 @return: Spherical excess (C{radians}).

618

619 @raise UnitError: Invalid B{C{A}}, B{C{B}} or B{C{C}}.

620

621 @see: Function L{excessLHuilier_} and U{Spherical trigonometry

622 <https://WikiPedia.org/wiki/Spherical_trigonometry>}.

623 '''

624 return Radians(Girard=fsumf_(Radians_(A=A),

625 Radians_(B=B),

626 Radians_(C=C), -PI))

627

628

629 def excessLHuilier_(a, b, c):

630 '''Compute the I{spherical excess} C{E} of a (spherical) triangle using U{L'Huilier's

631 <https://MathWorld.Wolfram.com/LHuiliersTheorem.html>}'s Theorem.

632

633 @arg a: First triangle side (C{radians}).

634 @arg b: Second triangle side (C{radians}).

635 @arg c: Third triangle side (C{radians}).

636

637 @return: Spherical excess (C{radians}).

638

639 @raise UnitError: Invalid B{C{a}}, B{C{b}} or B{C{c}}.

640

641 @see: Function L{excessCagnoli_}, L{excessGirard_} and U{Spherical

642 trigonometry<https://WikiPedia.org/wiki/Spherical_trigonometry>}.

643 '''

644 a = Radians_(a=a)

645 b = Radians_(b=b)

646 c = Radians_(c=c)

647

648 s = fsumf_(a, b, c) * _0_5

649 _t = tan_2

650 r = _t(s) * _t(s - a) * _t(s - b) * _t(s - c)

651 r = atan(sqrt(r)) if r > 0 else _0_0

652 return Radians(LHuilier=r * _4_0)

653

654

655 def excessKarney(lat1, lon1, lat2, lon2, radius=R_M, wrap=False):

656 '''Compute the surface area of a (spherical) quadrilateral bounded by a

657 segment of a great circle, two meridians and the equator using U{Karney's

658 <https://MathOverflow.net/questions/97711/the-area-of-spherical-polygons>}

659 method.

660

661 @arg lat1: Start latitude (C{degrees}).

662 @arg lon1: Start longitude (C{degrees}).

663 @arg lat2: End latitude (C{degrees}).

664 @arg lon2: End longitude (C{degrees}).

665 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum})

666 or ellipsoid (L{Ellipsoid}, L{Ellipsoid2} or

667 L{a_f2Tuple}) or C{None}.

668 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll

669 B{C{lat2}} and B{C{lon2}} (C{bool}).

670

671 @return: Surface area, I{signed} (I{square} C{meter} or the same units as

672 B{C{radius}} I{squared}) or the I{spherical excess} (C{radians})

673 if C{B{radius}=0} or C{None}.

674

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

676

677 @raise UnitError: Invalid B{C{lat2}} or B{C{lat1}}.

678

679 @raise ValueError: Semi-circular longitudinal delta.

680

681 @see: Functions L{excessKarney_} and L{excessQuad}.

682 '''

683 return _eA(excessKarney_, radius, wrap, lat1, lon1, lat2, lon2)

684

685

686 def excessKarney_(phi2, phi1, lam21):

687 '''Compute the I{spherical excess} C{E} of a (spherical) quadrilateral bounded by

688 a segment of a great circle, two meridians and the equator using U{Karney's

689 <https://MathOverflow.net/questions/97711/the-area-of-spherical-polygons>}

690 method.

691

692 @arg phi2: End latitude (C{radians}).

693 @arg phi1: Start latitude (C{radians}).

694 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).

695

696 @return: Spherical excess, I{signed} (C{radians}).

697

698 @raise ValueError: Semi-circular longitudinal delta B{C{lam21}}.

699

700 @see: Function L{excessKarney} and U{Area of a spherical polygon

701 <https://MathOverflow.net/questions/97711/the-area-of-spherical-polygons>}.

702 '''

703 # from: Veness <https://www.Movable-Type.co.UK/scripts/latlong.html> Area

704 # method due to Karney: for each edge of the polygon,

705 #

706 # tan(Δλ / 2) · (tan(φ1 / 2) + tan(φ2 / 2))

707 # tan(E / 2) = -----------------------------------------

708 # 1 + tan(φ1 / 2) · tan(φ2 / 2)

709 #

710 # where E is the spherical excess of the trapezium obtained by extending

711 # the edge to the equator-circle vector for each edge (see also ***).

712 _t = tan_2

713 t2 = _t(phi2)

714 t1 = _t(phi1)

715 t = _t(lam21, lam21=None)

716 return Radians(Karney=atan2(t * (t1 + t2),

717 _1_0 + (t1 * t2)) * _2_0)

718

719

720# ***) Original post no longer available, following is a copy of the main part

721# <http://OSGeo-org.1560.x6.Nabble.com/Area-of-a-spherical-polygon-td3841625.html>

722#

723# The area of a polygon on a (unit) sphere is given by the spherical excess

724#

725# A = 2 * pi - sum(exterior angles)

726#

727# However this is badly conditioned if the polygon is small. In this case, use

728#

729# A = sum(S12{i, i+1}) over the edges of the polygon

730#

731# where S12 is the area of the quadrilateral bounded by an edge of the polygon,

732# two meridians and the equator, i.e. with vertices (phi1, lambda1), (phi2,

733# lambda2), (0, lambda1) and (0, lambda2). S12 is given by

734#

735# tan(S12 / 2) = tan(lambda21 / 2) * (tan(phi1 / 2) + tan(phi2 / 2)) /

736# (tan(phi1 / 2) * tan(phi2 / 2) + 1)

737#

738# = tan(lambda21 / 2) * tanh((Lamb(phi1) + Lamb(phi2)) / 2)

739#

740# where lambda21 = lambda2 - lambda1 and Lamb(x) is the Lambertian (or the

741# inverse Gudermannian) function

742#

743# Lambertian(x) = asinh(tan(x)) = atanh(sin(x)) = 2 * atanh(tan(x / 2))

744#

745# Notes: The formula for S12 is exact, except that...

746# - it is indeterminate if an edge is a semi-circle

747# - the formula for A applies only if the polygon does not include a pole

748# (if it does, then add +/- 2 * pi to the result)

749# - in the limit of small phi and lambda, S12 reduces to the trapezoidal

750# formula, S12 = (lambda2 - lambda1) * (phi1 + phi2) / 2

751# - I derived this result from the equation for the area of a spherical

752# triangle in terms of two edges and the included angle given by, e.g.

753# U{Todhunter, I. - Spherical Trigonometry (1871), Sec. 103, Eq. (2)

754# <http://Books.Google.com/books?id=3uBHAAAAIAAJ&pg=PA71>}

755# - I would be interested to know if this formula for S12 is already known

756# - Charles Karney

757

758

759 def excessQuad(lat1, lon1, lat2, lon2, radius=R_M, wrap=False):

760 '''Compute the surface area of a (spherical) quadrilateral bounded by a segment

761 of a great circle, two meridians and the equator.

762

763 @arg lat1: Start latitude (C{degrees}).

764 @arg lon1: Start longitude (C{degrees}).

765 @arg lat2: End latitude (C{degrees}).

766 @arg lon2: End longitude (C{degrees}).

767 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum})

768 or ellipsoid (L{Ellipsoid}, L{Ellipsoid2} or

769 L{a_f2Tuple}) or C{None}.

770 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll

771 B{C{lat2}} and B{C{lon2}} (C{bool}).

772

773 @return: Surface area, I{signed} (I{square} C{meter} or the same units as

774 B{C{radius}} I{squared}) or the I{spherical excess} (C{radians})

775 if C{B{radius}=0} or C{None}.

776

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

778

779 @raise UnitError: Invalid B{C{lat2}} or B{C{lat1}}.

780

781 @see: Function L{excessQuad_} and L{excessKarney}.

782 '''

783 return _eA(excessQuad_, radius, wrap, lat1, lon1, lat2, lon2)

784

785

786 def excessQuad_(phi2, phi1, lam21):

787 '''Compute the I{spherical excess} C{E} of a (spherical) quadrilateral bounded

788 by a segment of a great circle, two meridians and the equator.

789

790 @arg phi2: End latitude (C{radians}).

791 @arg phi1: Start latitude (C{radians}).

792 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).

793

794 @return: Spherical excess, I{signed} (C{radians}).

795

796 @see: Function L{excessQuad} and U{Spherical trigonometry

797 <https://WikiPedia.org/wiki/Spherical_trigonometry>}.

798 '''

799 s = sin((phi2 + phi1) * _0_5)

800 c = cos((phi2 - phi1) * _0_5)

801 return Radians(Quad=atan2(tan_2(lam21) * s, c) * _2_0)

802

803

804 def flatLocal(lat1, lon1, lat2, lon2, datum=_WGS84, scaled=True, wrap=False):

805 '''Compute the distance between two (ellipsoidal) points using

806 the U{ellipsoidal Earth to plane projection<https://WikiPedia.org/

807 wiki/Geographical_distance#Ellipsoidal_Earth_projected_to_a_plane>}

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

809

810 @arg lat1: Start latitude (C{degrees}).

811 @arg lon1: Start longitude (C{degrees}).

812 @arg lat2: End latitude (C{degrees}).

813 @arg lon2: End longitude (C{degrees}).

814 @kwarg datum: Datum (L{Datum}) or ellipsoid (L{Ellipsoid},

815 L{Ellipsoid2} or L{a_f2Tuple}) to use.

816 @kwarg scaled: Scale prime_vertical by C{cos(B{phi})} (C{bool}),

817 see method L{pygeodesy.Ellipsoid.roc2_}.

818 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll

819 B{C{lat2}} and B{C{lon2}} (C{bool}).

820

821 @return: Distance (C{meter}, same units as the B{C{datum}}'s

822 ellipsoid axes).

823

824 @raise TypeError: Invalid B{C{datum}}.

825

826 @note: The meridional and prime_vertical radii of curvature

827 are taken and scaled at the mean of both latitude.

828

829 @see: Functions L{flatLocal_} or L{hubeny_}, L{cosineLaw}, L{flatPolar},

830 L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

831 L{equirectangular}, L{euclidean}, L{haversine}, L{thomas},

832 L{vincentys}, method L{Ellipsoid.distance2} and U{local, flat

833 earth approximation<https://www.EdWilliams.org/avform.htm#flat>}.

834 '''

835 E = _ellipsoidal(datum, flatLocal)

836 return E._hubeny_2(*_d3(wrap, lat1, lon1, lat2, lon2),

837 scaled=scaled, squared=False) * E.a

838

839 hubeny = flatLocal # PYCHOK for Karl Hubeny

840

841

842 def flatLocal_(phi2, phi1, lam21, datum=_WGS84, scaled=True):

843 '''Compute the I{angular} distance between two (ellipsoidal) points using

844 the U{ellipsoidal Earth to plane projection<https://WikiPedia.org/

845 wiki/Geographical_distance#Ellipsoidal_Earth_projected_to_a_plane>}

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

847

848 @arg phi2: End latitude (C{radians}).

849 @arg phi1: Start latitude (C{radians}).

850 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).

851 @kwarg datum: Datum (L{Datum}) or ellipsoid (L{Ellipsoid},

852 L{Ellipsoid2} or L{a_f2Tuple}) to use.

853 @kwarg scaled: Scale prime_vertical by C{cos(B{phi})} (C{bool}),

854 see method L{pygeodesy.Ellipsoid.roc2_}.

855

856 @return: Angular distance (C{radians}).

857

858 @raise TypeError: Invalid B{C{datum}}.

859

860 @note: The meridional and prime_vertical radii of curvature

861 are taken and scaled I{at the mean of both latitude}.

862

863 @see: Functions L{flatLocal} or L{hubeny}, L{cosineAndoyerLambert_},

864 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_}, L{flatPolar_},

865 L{euclidean_}, L{haversine_}, L{thomas_} and L{vincentys_} and

866 U{local, flat earth approximation

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

868 '''

869 E = _ellipsoidal(datum, flatLocal_)

870 return E._hubeny_2(phi2, phi1, lam21, scaled=scaled, squared=False)

871

872 hubeny_ = flatLocal_ # PYCHOK for Karl Hubeny

873

874

875 def flatPolar(lat1, lon1, lat2, lon2, radius=R_M, wrap=False):

876 '''Compute the distance between two (spherical) points using

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

878 Geographical_distance#Polar_coordinate_flat-Earth_formula>}

879 formula.

880

881 @arg lat1: Start latitude (C{degrees}).

882 @arg lon1: Start longitude (C{degrees}).

883 @arg lat2: End latitude (C{degrees}).

884 @arg lon2: End longitude (C{degrees}).

885 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum})

886 or ellipsoid (L{Ellipsoid}, L{Ellipsoid2} or

887 L{a_f2Tuple}) to use.

888 @kwarg wrap: If C{True}, wrap or I{normalize} and B{C{lat2}}

889 and B{C{lon2}} (C{bool}).

890

891 @return: Distance (C{meter}, same units as B{C{radius}} or the

892 ellipsoid or datum axes).

893

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

895

896 @see: Functions L{flatPolar_}, L{cosineAndoyerLambert},

897 L{cosineForsytheAndoyerLambert},L{cosineLaw},

898 L{flatLocal}/L{hubeny}, L{equirectangular},

899 L{euclidean}, L{haversine}, L{thomas} and

900 L{vincentys}.

901 '''

902 return _dS(flatPolar_, radius, wrap, lat1, lon1, lat2, lon2)

903

904

905 def flatPolar_(phi2, phi1, lam21):

906 '''Compute the I{angular} distance between two (spherical) points

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

908 Geographical_distance#Polar_coordinate_flat-Earth_formula>}

909 formula.

910

911 @arg phi2: End latitude (C{radians}).

912 @arg phi1: Start latitude (C{radians}).

913 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).

914

915 @return: Angular distance (C{radians}).

916

917 @see: Functions L{flatPolar}, L{cosineAndoyerLambert_},

918 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

919 L{euclidean_}, L{flatLocal_}/L{hubeny_}, L{haversine_},

920 L{thomas_} and L{vincentys_}.

921 '''

922 a = fabs(PI_2 - phi1) # co-latitude

923 b = fabs(PI_2 - phi2) # co-latitude

924 if a < b:

925 a, b = b, a

926 if a < EPS0:

927 a = _0_0

928 elif b > 0:

929 b = b / a # /= chokes PyChecker

930 c = b * cos(lam21) * _2_0

931 c = fsumf_(_1_0, b**2, -fabs(c))

932 a *= sqrt0(c)

933 return a

934

935

936 def _hartzell(pov, los, earth, **kwds):

937 '''(INTERNAL) Helper for C{CartesianBase.hartzell} and C{LatLonBase.hartzell}.

938 '''

939 if earth is None:

940 earth = pov.datum

941 else:

942 earth = _spherical_datum(earth, name__=hartzell)

943 pov = pov.toDatum(earth)

944 h = pov.height

945 if h < 0: # EPS0

946 t = _SPACE_(Fmt.PARENSPACED(height=h), _inside_)

947 raise IntersectionError(pov=pov, earth=earth, txt=t)

948 return hartzell(pov, los=los, earth=earth, **kwds) if h > 0 else pov # EPS0

949

950

951 def hartzell(pov, los=False, earth=_WGS84, **name_LatLon_and_kwds):

952 '''Compute the intersection of the earth's surface and a Line-Of-Sight from

953 a Point-Of-View in space.

954

955 @arg pov: Point-Of-View outside the earth (C{LatLon}, C{Cartesian},

956 L{Ecef9Tuple} or L{Vector3d}).

957 @kwarg los: Line-Of-Sight, I{direction} to earth (L{Los}, L{Vector3d}),

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

959 or C{None} to point to the center of the earth.

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

961 L{a_f2Tuple} or a C{scalar} earth radius in C{meter}).

962 @kwarg name_LatLon_and_kwds: Optional, overriding C{B{name}="hartzell"}

963 (C{str}), class C{B{LatLon}=None} to return the intersection

964 plus additional C{LatLon} keyword arguments, include the

965 B{C{datum}} if different and to convert from B{C{earth}}.

966

967 @return: The intersection (L{Vector3d}, B{C{pov}}'s C{cartesian type} or the

968 given B{C{LatLon}} instance) with attribute C{heigth} set to the

969 distance to the B{C{pov}}.

970

971 @raise IntersectionError: Invalid B{C{pov}} or B{C{pov}} inside the earth or

972 invalid B{C{los}} or B{C{los}} points outside or

973 away from the earth.

974

975 @raise TypeError: Invalid B{C{earth}}, C{ellipsoid} or C{datum}.

976

977 @see: Class L{Los}, functions L{tyr3d} and L{hartzell4} and methods

978 L{Ellipsoid.hartzell4} and any C{Cartesian.hartzell} and C{LatLon.hartzell}.

979 '''

980 n, LatLon_and_kwds = _name2__(name_LatLon_and_kwds, name__=hartzell)

981 try:

982 D = _spherical_datum(earth, name__=hartzell)

983 r, h, i = _MODS.triaxials._hartzell3(pov, los, D.ellipsoid._triaxial)

984

985 C = _MODS.cartesianBase.CartesianBase

986 if LatLon_and_kwds:

987 c = C(r, datum=D)

988 r = c.toLatLon(**_xkwds(LatLon_and_kwds, height=h))

989 elif isinstance(r, C):

990 r.height = h

991 if i:

992 r._iteration = i

993 except Exception as x:

994 raise IntersectionError(pov=pov, los=los, earth=earth, cause=x,

995 **LatLon_and_kwds)

996 return _xnamed(r, n) if n else r

997

998

999 def haversine(lat1, lon1, lat2, lon2, radius=R_M, wrap=False):

1000 '''Compute the distance between two (spherical) points using the

1001 U{Haversine<https://www.Movable-Type.co.UK/scripts/latlong.html>}

1002 formula.

1003

1004 @arg lat1: Start latitude (C{degrees}).

1005 @arg lon1: Start longitude (C{degrees}).

1006 @arg lat2: End latitude (C{degrees}).

1007 @arg lon2: End longitude (C{degrees}).

1008 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum})

1009 or ellipsoid (L{Ellipsoid}, L{Ellipsoid2} or

1010 L{a_f2Tuple}) to use.

1011 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll

1012 B{C{lat2}} and B{C{lon2}} (C{bool}).

1013

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

1015

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

1017

1018 @see: U{Distance between two (spherical) points

1019 <https://www.EdWilliams.org/avform.htm#Dist>}, functions

1020 L{cosineLaw}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

1021 L{equirectangular}, L{euclidean}, L{flatLocal}/L{hubeny}, L{flatPolar},

1022 L{thomas} and L{vincentys} and methods L{Ellipsoid.distance2},

1023 C{LatLon.distanceTo*} and C{LatLon.equirectangularTo}.

1024

1025 @note: See note at function L{vincentys_}.

1026 '''

1027 return _dS(haversine_, radius, wrap, lat1, lon1, lat2, lon2)

1028

1029

1030 def haversine_(phi2, phi1, lam21):

1031 '''Compute the I{angular} distance between two (spherical) points

1032 using the U{Haversine<https://www.Movable-Type.co.UK/scripts/latlong.html>}

1033 formula.

1034

1035 @arg phi2: End latitude (C{radians}).

1036 @arg phi1: Start latitude (C{radians}).

1037 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).

1038

1039 @return: Angular distance (C{radians}).

1040

1041 @see: Functions L{haversine}, L{cosineAndoyerLambert_},

1042 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

1043 L{euclidean_}, L{flatLocal_}/L{hubeny_}, L{flatPolar_},

1044 L{thomas_} and L{vincentys_}.

1045

1046 @note: See note at function L{vincentys_}.

1047 '''

1048 def _hsin(rad):

1049 return sin(rad * _0_5)**2

1050

1051 h = _hsin(phi2 - phi1) + cos(phi1) * cos(phi2) * _hsin(lam21) # haversine

1052 return atan2(sqrt0(h), sqrt0(_1_0 - h)) * _2_0 # == asin(sqrt(h)) * 2

1053

1054

1055 def heightOf(angle, distance, radius=R_M):

1056 '''Determine the height above the (spherical) earth' surface after

1057 traveling along a straight line at a given tilt.

1058

1059 @arg angle: Tilt angle above horizontal (C{degrees}).

1060 @arg distance: Distance along the line (C{meter} or same units as

1061 B{C{radius}}).

1062 @kwarg radius: Optional mean earth radius (C{meter}).

1063

1064 @return: Height (C{meter}, same units as B{C{distance}} and B{C{radius}}).

1065

1066 @raise ValueError: Invalid B{C{angle}}, B{C{distance}} or B{C{radius}}.

1067

1068 @see: U{MultiDop geog_lib.GeogBeamHt<https://GitHub.com/NASA/MultiDop>}

1069 (U{Shapiro et al. 2009, JTECH

1070 <https://Journals.AMetSoc.org/doi/abs/10.1175/2009JTECHA1256.1>}

1071 and U{Potvin et al. 2012, JTECH

1072 <https://Journals.AMetSoc.org/doi/abs/10.1175/JTECH-D-11-00019.1>}).

1073 '''

1074 r = h = Radius(radius)

1075 d = fabs(Distance(distance))

1076 if d > h:

1077 d, h = h, d

1078

1079 if d > EPS0: # and h > EPS0

1080 d = d / h # /= h chokes PyChecker

1081 s = sin(Phi_(angle=angle, clip=_180_0))

1082 s = fsumf_(_1_0, s * d * _2_0, d**2)

1083 if s > 0:

1084 return h * sqrt(s) - r

1085

1086 raise _ValueError(angle=angle, distance=distance, radius=radius)

1087

1088

1089 def heightOrthometric(h_ll, N):

1090 '''Get the I{orthometric} height B{H}, the height above the geoid, earth surface.

1091

1092 @arg h_ll: The height above the ellipsoid (C{meter}) or an I{ellipsoidal}

1093 location (C{LatLon} with a C{height} or C{h} attribute).

1094 @arg N: The I{geoid} height (C{meter}), the height of the geoid above the

1095 ellipsoid at the same B{C{h_ll}} location.

1096

1097 @return: I{Orthometric} height C{B{H} = B{h} - B{N}} (C{meter}, same units

1098 as B{C{h}} and B{C{N}}).

1099

1100 @see: U{Ellipsoid, Geoid, and Othometric Heights<https://www.NGS.NOAA.gov/

1101 GEOID/PRESENTATIONS/2007_02_24_CCPS/Roman_A_PLSC2007notes.pdf>}, page

1102 6 and module L{pygeodesy.geoids}.

1103 '''

1104 h = h_ll if _isHeight(h_ll) else _xattr(h_ll, height=_xattr(h_ll, h=0))

1105 return Height(H=Height(h=h) - Height(N=N))

1106

1107

1108 def horizon(height, radius=R_M, refraction=False):

1109 '''Determine the distance to the horizon from a given altitude above the

1110 (spherical) earth.

1111

1112 @arg height: Altitude (C{meter} or same units as B{C{radius}}).

1113 @kwarg radius: Optional mean earth radius (C{meter}).

1114 @kwarg refraction: Consider atmospheric refraction (C{bool}).

1115

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

1117

1118 @raise ValueError: Invalid B{C{height}} or B{C{radius}}.

1119

1120 @see: U{Distance to horizon<https://www.EdWilliams.org/avform.htm#Horizon>}.

1121 '''

1122 h, r = Height(height), Radius(radius)

1123 if min(h, r) < 0:

1124 raise _ValueError(height=height, radius=radius)

1125

1126 d2 = ((r * 2.415750694528) if refraction else # 2.0 / 0.8279

1127 fsumf_(r, r, h)) * h

1128 return sqrt0(d2)

1129

1130

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

1132 '''(INTERNAL) Helper for C{intersection2} and C{intersections2}.

1133 '''

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

1135 def __call__(self, datum, lat1, lon1, lat2, lon2, small, wrap, s, **kwds):

1136 try:

1137 if wrap:

1138 _, lat2, lon2 = _Wrap.latlon3(lon1, lat2, lon2, wrap)

1139 kwds = _xkwds(kwds, wrap=wrap) # for _xError

1140 m = small if small is _100km else Meter_(small=small)

1141 n = _dunder_nameof(intersections2 if s else intersection2)

1142 if datum is None or euclidean(lat1, lon1, lat2, lon2) < m:

1143 d, m = None, _MODS.vector3d

1144 _i = m._intersects2 if s else m._intersect3d3

1145 elif _isRadius(datum) and datum < 0 and not s:

1146 d = _spherical_datum(-datum, name=n)

1147 m = _MODS.sphericalNvector

1148 _i = m.intersection

1149 else:

1150 d = _spherical_datum(datum, name=n)

1151 if d.isSpherical:

1152 m = _MODS.sphericalTrigonometry

1153 _i = m._intersects2 if s else m._intersect

1154 elif d.isEllipsoidal:

1155 try:

1156 if d.ellipsoid.geodesic:

1157 pass

1158 m = _MODS.ellipsoidalKarney

1159 except ImportError:

1160 m = _MODS.ellipsoidalExact

1161 _i = m._intersections2 if s else m._intersection3 # ellispoidalBaseDI

1162 else:

1163 raise _TypeError(datum=datum)

1164 yield _i, d, lat2, lon2, m, n

1165

1166 except (TypeError, ValueError) as x:

1167 raise _xError(x, lat1=lat1, lon1=lon1, datum=datum,

1168 lat2=lat2, lon2=lon2, small=small, **kwds)

1169

1170_idllmn6 = _idllmn6() # PYCHOK singleton

1171

1172

1173 def intersection2(lat1, lon1, bearing1,

1174 lat2, lon2, bearing2, datum=None, wrap=False, small=_100km): # was=True

1175 '''I{Conveniently} compute the intersection of two lines each defined

1176 by a (geodetic) point and a bearing from North, using either ...

1177

1178 1) L{vector3d.intersection3d3} for B{C{small}} distances (below 100 Km

1179 or about 0.88 degrees) or if I{no} B{C{datum}} is specified, or ...

1180

1181 2) L{sphericalTrigonometry.intersection} for a spherical B{C{datum}}

1182 or a C{scalar B{datum}} representing the earth radius, conventionally

1183 in C{meter} or ...

1184

1185 3) L{sphericalNvector.intersection} if B{C{datum}} is a I{negative}

1186 C{scalar}, (negative) earth radius, conventionally in C{meter} or ...

1187

1188 4) L{ellipsoidalKarney.intersection3} for an ellipsoidal B{C{datum}}

1189 and if I{Karney}'s U{geographiclib<https://PyPI.org/project/geographiclib>}

1190 is installed, otherwise ...

1191

1192 5) L{ellipsoidalExact.intersection3}, provided B{C{datum}} is ellipsoidal.

1193

1194 @arg lat1: Latitude of the first point (C{degrees}).

1195 @arg lon1: Longitude of the first point (C{degrees}).

1196 @arg bearing1: Bearing at the first point (compass C{degrees}).

1197 @arg lat2: Latitude of the second point (C{degrees}).

1198 @arg lon2: Longitude of the second point (C{degrees}).

1199 @arg bearing2: Bearing at the second point (compass C{degrees}).

1200 @kwarg datum: Optional datum (L{Datum}) or ellipsoid (L{Ellipsoid},

1201 L{Ellipsoid2} or L{a_f2Tuple}) or C{scalar} earth

1202 radius (C{meter}, same units as B{C{radius1}} and

1203 B{C{radius2}}) or C{None}.

1204 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll B{C{lat2}}

1205 and B{C{lon2}} (C{bool}).

1206 @kwarg small: Upper limit for small distances (C{meter}).

1207

1208 @return: A L{LatLon2Tuple}C{(lat, lon)} with the lat- and

1209 longitude of the intersection point.

1210

1211 @raise IntersectionError: Ambiguous or infinite intersection

1212 or colinear, parallel or otherwise

1213 non-intersecting lines.

1214

1215 @raise TypeError: Invalid B{C{datum}}.

1216

1217 @raise UnitError: Invalid B{C{lat1}}, B{C{lon1}}, B{C{bearing1}},

1218 B{C{lat2}}, B{C{lon2}} or B{C{bearing2}}.

1219

1220 @see: Method L{RhumbLine.intersection2}.

1221

1222 @note: The returned intersections may be near-antipodal.

1223 '''

1224 b1 = Bearing(bearing1=bearing1)

1225 b2 = Bearing(bearing2=bearing2)

1226 with _idllmn6(datum, lat1, lon1, lat2, lon2,

1227 small, wrap, False, bearing1=b1, bearing2=b2) as t:

1228 _i, d, lat2, lon2, m, n = t

1229 if d is None:

1230 t, _, _ = _i(m.Vector3d(lon1, lat1, 0), b1,

1231 m.Vector3d(lon2, lat2, 0), b2, useZ=False)

1232 t = LatLon2Tuple(t.y, t.x, name=n)

1233

1234 else:

1235 t = _i(m.LatLon(lat1, lon1, datum=d), b1,

1236 m.LatLon(lat2, lon2, datum=d), b2, height=0, wrap=False)

1237 if isinstance(t, Intersection3Tuple): # ellipsoidal

1238 t, _, _ = t

1239 t = LatLon2Tuple(t.lat, t.lon, name=n)

1240 return t

1241

1242

1243 def intersections2(lat1, lon1, radius1,

1244 lat2, lon2, radius2, datum=None, wrap=False, small=_100km): # was=True

1245 '''I{Conveniently} compute the intersections of two circles each defined

1246 by a (geodetic) center point and a radius, using either ...

1247

1248 1) L{vector3d.intersections2} for B{C{small}} distances (below 100 Km

1249 or about 0.88 degrees) or if I{no} B{C{datum}} is specified, or ...

1250

1251 2) L{sphericalTrigonometry.intersections2} for a spherical B{C{datum}}

1252 or a C{scalar B{datum}} representing the earth radius, conventionally

1253 in C{meter} or ...

1254

1255 3) L{ellipsoidalKarney.intersections2} for an ellipsoidal B{C{datum}}

1256 and if I{Karney}'s U{geographiclib<https://PyPI.org/project/geographiclib>}

1257 is installed, otherwise ...

1258

1259 4) L{ellipsoidalExact.intersections2}, provided B{C{datum}} is ellipsoidal.

1260

1261 @arg lat1: Latitude of the first circle center (C{degrees}).

1262 @arg lon1: Longitude of the first circle center (C{degrees}).

1263 @arg radius1: Radius of the first circle (C{meter}, conventionally).

1264 @arg lat2: Latitude of the second circle center (C{degrees}).

1265 @arg lon2: Longitude of the second circle center (C{degrees}).

1266 @arg radius2: Radius of the second circle (C{meter}, same units as B{C{radius1}}).

1267 @kwarg datum: Optional datum (L{Datum}) or ellipsoid (L{Ellipsoid},

1268 L{Ellipsoid2} or L{a_f2Tuple}) or C{scalar} earth

1269 radius (C{meter}, same units as B{C{radius1}} and

1270 B{C{radius2}}) or C{None}.

1271 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll B{C{lat2}}

1272 and B{C{lon2}} (C{bool}).

1273 @kwarg small: Upper limit for small distances (C{meter}).

1274

1275 @return: 2-Tuple of the intersection points, each a

1276 L{LatLon2Tuple}C{(lat, lon)}. For abutting circles, the

1277 points are the same instance, aka the I{radical center}.

1278

1279 @raise IntersectionError: Concentric, antipodal, invalid or

1280 non-intersecting circles or no

1281 convergence.

1282

1283 @raise TypeError: Invalid B{C{datum}}.

1284

1285 @raise UnitError: Invalid B{C{lat1}}, B{C{lon1}}, B{C{radius1}},

1286 B{C{lat2}}, B{C{lon2}} or B{C{radius2}}.

1287 '''

1288 r1 = Radius_(radius1=radius1)

1289 r2 = Radius_(radius2=radius2)

1290 with _idllmn6(datum, lat1, lon1, lat2, lon2,

1291 small, wrap, True, radius1=r1, radius2=r2) as t:

1292 _i, d, lat2, lon2, m, n = t

1293 if d is None:

1294 r1 = m2degrees(r1, radius=R_M, lat=lat1)

1295 r2 = m2degrees(r2, radius=R_M, lat=lat2)

1296

1297 def _V2T(x, y, _, **unused): # _ == z unused

1298 return LatLon2Tuple(y, x, name=n)

1299

1300 t = _i(m.Vector3d(lon1, lat1, 0), r1,

1301 m.Vector3d(lon2, lat2, 0), r2, sphere=False,

1302 Vector=_V2T)

1303 else:

1304 def _LL2T(lat, lon, **unused):

1305 return LatLon2Tuple(lat, lon, name=n)

1306

1307 t = _i(m.LatLon(lat1, lon1, datum=d), r1,

1308 m.LatLon(lat2, lon2, datum=d), r2,

1309 LatLon=_LL2T, height=0, wrap=False)

1310 return t

1311

1312

1313 def isantipode(lat1, lon1, lat2, lon2, eps=EPS):

1314 '''Check whether two points are I{antipodal}, on diametrically

1315 opposite sides of the earth.

1316

1317 @arg lat1: Latitude of one point (C{degrees}).

1318 @arg lon1: Longitude of one point (C{degrees}).

1319 @arg lat2: Latitude of the other point (C{degrees}).

1320 @arg lon2: Longitude of the other point (C{degrees}).

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

1322

1323 @return: C{True} if points are antipodal within the

1324 B{C{eps}} tolerance, C{False} otherwise.

1325

1326 @see: Functions L{isantipode_} and L{antipode}.

1327 '''

1328 return (fabs(lat1 + lat2) <= eps and

1329 fabs(lon1 + lon2) <= eps) or _isequalTo(

1330 normal(lat1, lon1), antipode(lat2, lon2), eps)

1331

1332

1333 def isantipode_(phi1, lam1, phi2, lam2, eps=EPS):

1334 '''Check whether two points are I{antipodal}, on diametrically

1335 opposite sides of the earth.

1336

1337 @arg phi1: Latitude of one point (C{radians}).

1338 @arg lam1: Longitude of one point (C{radians}).

1339 @arg phi2: Latitude of the other point (C{radians}).

1340 @arg lam2: Longitude of the other point (C{radians}).

1341 @kwarg eps: Tolerance for near-equality (C{radians}).

1342

1343 @return: C{True} if points are antipodal within the

1344 B{C{eps}} tolerance, C{False} otherwise.

1345

1346 @see: Functions L{isantipode} and L{antipode_}.

1347 '''

1348 return (fabs(phi1 + phi2) <= eps and

1349 fabs(lam1 + lam2) <= eps) or _isequalTo_(

1350 normal_(phi1, lam1), antipode_(phi2, lam2), eps)

1351

1352

1353 def _isequalTo(p1, p2, eps=EPS):

1354 '''Compare 2 point lat-/lons ignoring C{class}.

1355 '''

1356 return (fabs(p1.lat - p2.lat) <= eps and

1357 fabs(p1.lon - p2.lon) <= eps) if eps else (p1.latlon == p2.latlon)

1358

1359

1360 def _isequalTo_(p1, p2, eps=EPS):

1361 '''(INTERNAL) Compare 2 point phi-/lams ignoring C{class}.

1362 '''

1363 return (fabs(p1.phi - p2.phi) <= eps and

1364 fabs(p1.lam - p2.lam) <= eps) if eps else (p1.philam == p2.philam)

1365

1366

1367 def isnormal(lat, lon, eps=0):

1368 '''Check whether B{C{lat}} I{and} B{C{lon}} are within their

1369 respective I{normal} range in C{degrees}.

1370

1371 @arg lat: Latitude (C{degrees}).

1372 @arg lon: Longitude (C{degrees}).

1373 @kwarg eps: Optional tolerance C{degrees}).

1374

1375 @return: C{True} if C{(abs(B{lat}) + B{eps}) <= 90} and

1376 C{(abs(B{lon}) + B{eps}) <= 180}, C{False} othwerwise.

1377

1378 @see: Functions L{isnormal_} and L{normal}.

1379 '''

1380 return (_90_0 - fabs(lat)) >= eps and _loneg(fabs(lon)) >= eps

1381

1382

1383 def isnormal_(phi, lam, eps=0):

1384 '''Check whether B{C{phi}} I{and} B{C{lam}} are within their

1385 respective I{normal} range in C{radians}.

1386

1387 @arg phi: Latitude (C{radians}).

1388 @arg lam: Longitude (C{radians}).

1389 @kwarg eps: Optional tolerance C{radians}).

1390

1391 @return: C{True} if C{(abs(B{phi}) + B{eps}) <= PI/2} and

1392 C{(abs(B{lam}) + B{eps}) <= PI}, C{False} othwerwise.

1393

1394 @see: Functions L{isnormal} and L{normal_}.

1395 '''

1396 return (PI_2 - fabs(phi)) >= eps and (PI - fabs(lam)) >= eps

1397

1398

1399 def latlon2n_xyz(lat, lon, **name):

1400 '''Convert lat-, longitude to C{n-vector} (I{normal} to the

1401 earth's surface) X, Y and Z components.

1402

1403 @arg lat: Latitude (C{degrees}).

1404 @arg lon: Longitude (C{degrees}).

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

1406

1407 @return: A L{Vector3Tuple}C{(x, y, z)}.

1408

1409 @see: Function L{philam2n_xyz}.

1410

1411 @note: These are C{n-vector} x, y and z components,

1412 I{NOT} geocentric ECEF x, y and z coordinates!

1413 '''

1414 return _2n_xyz(name, *sincos2d_(lat, lon))

1415

1416

1417 def _normal2(a, b, n_2, n, n2):

1418 '''(INTERNAL) Helper for C{normal} and C{normal_}.

1419 '''

1420 if fabs(b) > n:

1421 b = remainder(b, n2)

1422 if fabs(a) > n_2:

1423 r = remainder(a, n)

1424 if r != a:

1425 a = -r

1426 b -= n if b > 0 else -n

1427 return float0_(a, b)

1428

1429

1430 def normal(lat, lon, **name):

1431 '''Normalize a lat- I{and} longitude pair in C{degrees}.

1432

1433 @arg lat: Latitude (C{degrees}).

1434 @arg lon: Longitude (C{degrees}).

1435 @kwarg name: Optional, overriding C{B{name}="normal"} (C{str}).

1436

1437 @return: L{LatLon2Tuple}C{(lat, lon)} with C{abs(lat) <= 90}

1438 and C{abs(lon) <= 180}.

1439

1440 @see: Functions L{normal_} and L{isnormal}.

1441 '''

1442 return LatLon2Tuple(*_normal2(lat, lon, _90_0, _180_0, _360_0),

1443 name=_name__(name, name__=normal))

1444

1445

1446 def normal_(phi, lam, **name):

1447 '''Normalize a lat- I{and} longitude pair in C{radians}.

1448

1449 @arg phi: Latitude (C{radians}).

1450 @arg lam: Longitude (C{radians}).

1451 @kwarg name: Optional, overriding C{B{name}="normal_"} (C{str}).

1452

1453 @return: L{PhiLam2Tuple}C{(phi, lam)} with C{abs(phi) <= PI/2}

1454 and C{abs(lam) <= PI}.

1455

1456 @see: Functions L{normal} and L{isnormal_}.

1457 '''

1458 return PhiLam2Tuple(*_normal2(phi, lam, PI_2, PI, PI2),

1459 name=_name__(name, name__=normal_))

1460

1461

1462 def _2n_xyz(name, sa, ca, sb, cb): # name always **name

1463 '''(INTERNAL) Helper for C{latlon2n_xyz} and C{philam2n_xyz}.

1464 '''

1465 # Kenneth Gade eqn 3, but using right-handed

1466 # vector x -> 0°E,0°N, y -> 90°E,0°N, z -> 90°N

1467 return Vector3Tuple(ca * cb, ca * sb, sa, **name)

1468

1469

1470 def n_xyz2latlon(x, y, z, **name):

1471 '''Convert C{n-vector} components to lat- and longitude in C{degrees}.

1472

1473 @arg x: X component (C{scalar}).

1474 @arg y: Y component (C{scalar}).

1475 @arg z: Z component (C{scalar}).

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

1477

1478 @return: A L{LatLon2Tuple}C{(lat, lon)}.

1479

1480 @see: Function L{n_xyz2philam}.

1481 '''

1482 return LatLon2Tuple(atan2d(z, hypot(x, y)), atan2d(y, x), **name)

1483

1484

1485 def n_xyz2philam(x, y, z, **name):

1486 '''Convert C{n-vector} components to lat- and longitude in C{radians}.

1487

1488 @arg x: X component (C{scalar}).

1489 @arg y: Y component (C{scalar}).

1490 @arg z: Z component (C{scalar}).

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

1492

1493 @return: A L{PhiLam2Tuple}C{(phi, lam)}.

1494

1495 @see: Function L{n_xyz2latlon}.

1496 '''

1497 return PhiLam2Tuple(atan2(z, hypot(x, y)), atan2(y, x), **name)

1498

1499

1500 def _opposes(d, m, n, n2):

1501 '''(INTERNAL) Helper for C{opposing} and C{opposing_}.

1502 '''

1503 d = d % n2 # -20 % 360 == 340, -1 % PI2 == PI2 - 1

1504 return False if d < m or d > (n2 - m) else (

1505 True if (n - m) < d < (n + m) else None)

1506

1507

1508 def opposing(bearing1, bearing2, margin=_90_0):

1509 '''Compare the direction of two bearings given in C{degrees}.

1510

1511 @arg bearing1: First bearing (compass C{degrees}).

1512 @arg bearing2: Second bearing (compass C{degrees}).

1513 @kwarg margin: Optional, interior angle bracket (C{degrees}).

1514

1515 @return: C{True} if both bearings point in opposite, C{False} if

1516 in similar or C{None} if in I{perpendicular} directions.

1517

1518 @see: Function L{opposing_}.

1519 '''

1520 m = Degrees_(margin=margin, low=EPS0, high=_90_0)

1521 return _opposes(bearing2 - bearing1, m, _180_0, _360_0)

1522

1523

1524 def opposing_(radians1, radians2, margin=PI_2):

1525 '''Compare the direction of two bearings given in C{radians}.

1526

1527 @arg radians1: First bearing (C{radians}).

1528 @arg radians2: Second bearing (C{radians}).

1529 @kwarg margin: Optional, interior angle bracket (C{radians}).

1530

1531 @return: C{True} if both bearings point in opposite, C{False} if

1532 in similar or C{None} if in perpendicular directions.

1533

1534 @see: Function L{opposing}.

1535 '''

1536 m = Radians_(margin=margin, low=EPS0, high=PI_2)

1537 return _opposes(radians2 - radians1, m, PI, PI2)

1538

1539

1540 def philam2n_xyz(phi, lam, **name):

1541 '''Convert lat-, longitude to C{n-vector} (I{normal} to the

1542 earth's surface) X, Y and Z components.

1543

1544 @arg phi: Latitude (C{radians}).

1545 @arg lam: Longitude (C{radians}).

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

1547

1548 @return: A L{Vector3Tuple}C{(x, y, z)}.

1549

1550 @see: Function L{latlon2n_xyz}.

1551

1552 @note: These are C{n-vector} x, y and z components,

1553 I{NOT} geocentric ECEF x, y and z coordinates!

1554 '''

1555 return _2n_xyz(name, *sincos2_(phi, lam))

1556

1557

1558 def _Propy(func, nargs, kwds):

1559 '''(INTERNAL) Helper for the C{frechet.[-]Frechet**} and

1560 C{hausdorff.[-]Hausdorff*} classes.

1561 '''

1562 try:

1563 _xcallable(distance=func)

1564 # assert _args_kwds_count2(func)[0] == nargs + int(ismethod(func))

1565 _ = func(*_0_0s(nargs), **kwds)

1566 except Exception as x:

1567 t = unstr(func, **kwds)

1568 raise _TypeError(t, cause=x)

1569 return func

1570

1571

1572 def _radical2(d, r1, r2, **name): # in .ellipsoidalBaseDI, .sphericalTrigonometry, .vector3d

1573 # (INTERNAL) See C{radical2} below

1574 # assert d > EPS0

1575 r = fsumf_(_1_0, (r1 / d)**2, -(r2 / d)**2) * _0_5

1576 n = _name__(name, name__=radical2)

1577 return Radical2Tuple(max(_0_0, min(_1_0, r)), r * d, name=n)

1578

1579

1580 def radical2(distance, radius1, radius2, **name):

1581 '''Compute the I{radical ratio} and I{radical line} of two

1582 U{intersecting circles<https://MathWorld.Wolfram.com/

1583 Circle-CircleIntersection.html>}.

1584

1585 The I{radical line} is perpendicular to the axis thru the

1586 centers of the circles at C{(0, 0)} and C{(B{distance}, 0)}.

1587

1588 @arg distance: Distance between the circle centers (C{scalar}).

1589 @arg radius1: Radius of the first circle (C{scalar}).

1590 @arg radius2: Radius of the second circle (C{scalar}).

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

1592

1593 @return: A L{Radical2Tuple}C{(ratio, xline)} where C{0.0 <=

1594 ratio <= 1.0} and C{xline} is along the B{C{distance}}.

1595

1596 @raise IntersectionError: The B{C{distance}} exceeds the sum

1597 of B{C{radius1}} and B{C{radius2}}.

1598

1599 @raise UnitError: Invalid B{C{distance}}, B{C{radius1}} or

1600 B{C{radius2}}.

1601

1602 @see: U{Circle-Circle Intersection

1603 <https://MathWorld.Wolfram.com/Circle-CircleIntersection.html>}.

1604 '''

1605 d = Distance_(distance, low=_0_0)

1606 r1 = Radius_(radius1=radius1)

1607 r2 = Radius_(radius2=radius2)

1608 if d > (r1 + r2):

1609 raise IntersectionError(distance=d, radius1=r1, radius2=r2,

1610 txt=_too_(_distant_))

1611 return _radical2(d, r1, r2, **name) if d > EPS0 else \

1612 Radical2Tuple(_0_5, _0_0, **name)

1613

1614

1615 class Radical2Tuple(_NamedTuple):

1616 '''2-Tuple C{(ratio, xline)} of the I{radical} C{ratio} and

1617 I{radical} C{xline}, both C{scalar} and C{0.0 <= ratio <= 1.0}

1618 '''

1619 _Names_ = (_ratio_, _xline_)

1620 _Units_ = ( Scalar, Scalar)

1621

1622

1623 def _radistance(inst):

1624 '''(INTERNAL) Helper for the L{frechet._FrechetMeterRadians}

1625 and L{hausdorff._HausdorffMeterRedians} classes.

1626 '''

1627 wrap_, kwds_ = _xkwds_pop2(inst._kwds, wrap=False)

1628 func_ = inst._func_

1629 try: # calling lower-overhead C{func_}

1630 func_(0, _0_25, _0_5, **kwds_)

1631 wrap_ = _Wrap._philamop(wrap_)

1632 except TypeError:

1633 return inst.distance

1634

1635 def _philam(p):

1636 try:

1637 return p.phi, p.lam

1638 except AttributeError: # no .phi or .lam

1639 return radians(p.lat), radians(p.lon)

1640

1641 def _func_wrap(point1, point2):

1642 phi1, lam1 = wrap_(*_philam(point1))

1643 phi2, lam2 = wrap_(*_philam(point2))

1644 return func_(phi2, phi1, lam2 - lam1, **kwds_)

1645

1646 inst._units = inst._units_

1647 return _func_wrap

1648

1649

1650 def _scale_deg(lat1, lat2): # degrees

1651 # scale factor cos(mean of lats) for delta lon

1652 m = fabs(lat1 + lat2) * _0_5

1653 return cos(radians(m)) if m < 90 else _0_0

1654

1655

1656 def _scale_rad(phi1, phi2): # radians, by .frechet, .hausdorff, .heights

1657 # scale factor cos(mean of phis) for delta lam

1658 m = fabs(phi1 + phi2) * _0_5

1659 return cos(m) if m < PI_2 else _0_0

1660

1661

1662 def _sincosa6(phi2, phi1, lam21): # [4] in cosineLaw

1663 '''(INTERNAL) C{sin}es, C{cos}ines and C{acos}ine.

1664 '''

1665 s2, c2, s1, c1, _, c21 = sincos2_(phi2, phi1, lam21)

1666 return s2, c2, s1, c1, acos1(s1 * s2 + c1 * c2 * c21), c21

1667

1668

1669 def thomas(lat1, lon1, lat2, lon2, datum=_WGS84, wrap=False):

1670 '''Compute the distance between two (ellipsoidal) points using

1671 U{Thomas'<https://apps.DTIC.mil/dtic/tr/fulltext/u2/703541.pdf>}

1672 formula.

1673

1674 @arg lat1: Start latitude (C{degrees}).

1675 @arg lon1: Start longitude (C{degrees}).

1676 @arg lat2: End latitude (C{degrees}).

1677 @arg lon2: End longitude (C{degrees}).

1678 @kwarg datum: Datum (L{Datum}) or ellipsoid (L{Ellipsoid},

1679 L{Ellipsoid2} or L{a_f2Tuple}) to use.

1680 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll

1681 B{C{lat2}} and B{C{lon2}} (C{bool}).

1682

1683 @return: Distance (C{meter}, same units as the B{C{datum}}'s

1684 ellipsoid axes).

1685

1686 @raise TypeError: Invalid B{C{datum}}.

1687

1688 @see: Functions L{thomas_}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

1689 L{cosineLaw}, L{equirectangular}, L{euclidean}, L{flatLocal}/L{hubeny},

1690 L{flatPolar}, L{haversine}, L{vincentys} and method L{Ellipsoid.distance2}.

1691 '''

1692 return _dE(thomas_, datum, wrap, lat1, lon1, lat2, lon2)

1693

1694

1695 def thomas_(phi2, phi1, lam21, datum=_WGS84):

1696 '''Compute the I{angular} distance between two (ellipsoidal) points using

1697 U{Thomas'<https://apps.DTIC.mil/dtic/tr/fulltext/u2/703541.pdf>}

1698 formula.

1699

1700 @arg phi2: End latitude (C{radians}).

1701 @arg phi1: Start latitude (C{radians}).

1702 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).

1703 @kwarg datum: Datum or ellipsoid to use (L{Datum}, L{Ellipsoid},

1704 L{Ellipsoid2} or L{a_f2Tuple}).

1705

1706 @return: Angular distance (C{radians}).

1707

1708 @raise TypeError: Invalid B{C{datum}}.

1709

1710 @see: Functions L{thomas}, L{cosineAndoyerLambert_},

1711 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

1712 L{euclidean_}, L{flatLocal_}/L{hubeny_}, L{flatPolar_},

1713 L{haversine_} and L{vincentys_} and U{Geodesy-PHP

1714 <https://GitHub.com/jtejido/geodesy-php/blob/master/src/Geodesy/

1715 Distance/ThomasFormula.php>}.

1716 '''

1717 s2, c2, s1, c1, r, _ = _sincosa6(phi2, phi1, lam21)

1718 if r and isnon0(c1) and isnon0(c2):

1719 E = _ellipsoidal(datum, thomas_)

1720 if E.f:

1721 r1 = atan2(E.b_a * s1, c1)

1722 r2 = atan2(E.b_a * s2, c2)

1723

1724 j = (r2 + r1) * _0_5

1725 k = (r2 - r1) * _0_5

1726 sj, cj, sk, ck, h, _ = sincos2_(j, k, lam21 * _0_5)

1727

1728 h = fsumf_(sk**2, (ck * h)**2, -(sj * h)**2)

1729 u = _1_0 - h

1730 if isnon0(u) and isnon0(h):

1731 r = atan(sqrt0(h / u)) * 2 # == acos(1 - 2 * h)

1732 sr, cr = sincos2(r)

1733 if isnon0(sr):

1734 u = 2 * (sj * ck)**2 / u

1735 h = 2 * (sk * cj)**2 / h

1736 x = u + h

1737 y = u - h

1738

1739 s = r / sr

1740 e = 4 * s**2

1741 d = 2 * cr

1742 a = e * d

1743 b = 2 * r

1744 c = s - (a - d) * _0_5

1745 f = E.f * _0_25

1746

1747 t = fsumf_(a * x, -b * y, c * x**2, -d * y**2, e * x * y)

1748 r -= fsumf_(s * x, -y, -t * f * _0_25) * f * sr

1749 return r

1750

1751

1752 def vincentys(lat1, lon1, lat2, lon2, radius=R_M, wrap=False):

1753 '''Compute the distance between two (spherical) points using

1754 U{Vincenty's<https://WikiPedia.org/wiki/Great-circle_distance>}

1755 spherical formula.

1756

1757 @arg lat1: Start latitude (C{degrees}).

1758 @arg lon1: Start longitude (C{degrees}).

1759 @arg lat2: End latitude (C{degrees}).

1760 @arg lon2: End longitude (C{degrees}).

1761 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum})

1762 or ellipsoid (L{Ellipsoid}, L{Ellipsoid2} or

1763 L{a_f2Tuple}) to use.

1764 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll

1765 B{C{lat2}} and B{C{lon2}} (C{bool}).

1766

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

1768

1769 @raise UnitError: Invalid B{C{radius}}.

1770

1771 @see: Functions L{vincentys_}, L{cosineAndoyerLambert},

1772 L{cosineForsytheAndoyerLambert},L{cosineLaw}, L{equirectangular},

1773 L{euclidean}, L{flatLocal}/L{hubeny}, L{flatPolar},

1774 L{haversine} and L{thomas} and methods L{Ellipsoid.distance2},

1775 C{LatLon.distanceTo*} and C{LatLon.equirectangularTo}.

1776

1777 @note: See note at function L{vincentys_}.

1778 '''

1779 return _dS(vincentys_, radius, wrap, lat1, lon1, lat2, lon2)

1780

1781

1782 def vincentys_(phi2, phi1, lam21):

1783 '''Compute the I{angular} distance between two (spherical) points using

1784 U{Vincenty's<https://WikiPedia.org/wiki/Great-circle_distance>}

1785 spherical formula.

1786

1787 @arg phi2: End latitude (C{radians}).

1788 @arg phi1: Start latitude (C{radians}).

1789 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).

1790

1791 @return: Angular distance (C{radians}).

1792

1793 @see: Functions L{vincentys}, L{cosineAndoyerLambert_},

1794 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

1795 L{euclidean_}, L{flatLocal_}/L{hubeny_}, L{flatPolar_},

1796 L{haversine_} and L{thomas_}.

1797

1798 @note: Functions L{vincentys_}, L{haversine_} and L{cosineLaw_}

1799 produce equivalent results, but L{vincentys_} is suitable

1800 for antipodal points and slightly more expensive (M{3 cos,

1801 3 sin, 1 hypot, 1 atan2, 6 mul, 2 add}) than L{haversine_}

1802 (M{2 cos, 2 sin, 2 sqrt, 1 atan2, 5 mul, 1 add}) and

1803 L{cosineLaw_} (M{3 cos, 3 sin, 1 acos, 3 mul, 1 add}).

1804 '''

1805 s1, c1, s2, c2, s21, c21 = sincos2_(phi1, phi2, lam21)

1806

1807 c = c2 * c21

1808 x = s1 * s2 + c1 * c

1809 y = c1 * s2 - s1 * c

1810 return atan2(hypot(c2 * s21, y), x)

1811

1812# **) MIT License

1813#

1814# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.

1815#

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

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

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

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

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

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

1822#

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

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

1825#

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

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

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

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

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

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

1832# OTHER DEALINGS IN THE SOFTWARE.