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.basics import isscalar # from .fsums

10# from pygeodesy.cartesianBase import CartesianBase # _MODS

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

12 _umod_PI2, float0_, isnon0, remainder, \

13 _0_0, _0_125, _0_25, _0_5, _1_0, _2_0, \

14 _4_0, _32_0, _90_0, _180_0, _360_0

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

16 _mean_radius, _spherical_datum, _WGS84, _EWGS84

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

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

19 _TypeError, _ValueError, _xattr, _xError, \

20 _xkwds, _xkwds_pop

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

22 from pygeodesy.fsums import fsumf_, isscalar

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

24 from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS

25 from pygeodesy.named import _NamedTuple, _xnamed, Fmt, unstr

26 from pygeodesy.namedTuples import Bearing2Tuple, Distance4Tuple, \

27 Intersection3Tuple, LatLon2Tuple, \

28 PhiLam2Tuple, Vector3Tuple

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

30# from pygeodesy.triaxials import _hartzell3d2 # _MODS

31 from pygeodesy.units import Bearing, Degrees_, Distance, Distance_, Height, \

32 Lam_, Lat, Lon, Meter_, Phi_, Radians, Radians_, \

33 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 import ellipsoidalExact, ellipsoidalKarney, vector3d, \

38# sphericalNvector, sphericalTrigonometry # _MODS

39

40 from contextlib import contextmanager

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

42

43__all__ = _ALL_LAZY.formy

44__version__ = '23.10.04'

45

46_D2_R2 = (PI / _180_0)**2 # degrees- to radians-squared

47_ratio_ = 'ratio'

48_xline_ = 'xline'

49

50

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

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

53 '''

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

55 if r == a:

56 r = -r

57 b += n

58 if fabs(b) > n:

59 b = remainder(b, n2)

60 return float0_(r, b)

61

62

63 def antipode(lat, lon, name=NN):

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

65 to a given point in C{degrees}.

66

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

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

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

70

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

72

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

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

75 '''

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

77

78

79 def antipode_(phi, lam, name=NN):

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

81 to a given point in C{radians}.

82

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

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

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

86

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

88

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

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

91 '''

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

93

94

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

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

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

98

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

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

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

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

103 @kwarg final_wrap: Optional keyword arguments for function

104 L{pygeodesy.bearing_}.

105

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

107 zero if start and end point coincide.

108 '''

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

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

111 return degrees(r)

112

113

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

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

116 between a (spherical) start and end point.

117

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

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

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

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

122 @kwarg final: Return final bearing if C{True}, initial otherwise (C{bool}).

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

124 B{C{lam2}} (C{bool}).

125

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

127 and end point coincide.

128

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

130 between two points<https://www.EdWilliams.org/avform147.htm#Crs>} and

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

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

133 '''

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

135 if final: # swap plus PI

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

137 r = PI3

138 else:

139 r = PI2

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

141

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

143 y = sdb * ca2

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

145

146

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

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

149 '''

150 try: # for LatLon_ and ellipsoidal LatLon

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

152 except AttributeError:

153 pass

154 # XXX spherical version, OK for ellipsoidal ispolar?

155 a1, b1 = p1.philam

156 a2, b2 = p2.philam

157 return Bearing2Tuple(degrees(bearing_(a1, b1, a2, b2, final=False, wrap=wrap)),

158 degrees(bearing_(a1, b1, a2, b2, final=True, wrap=wrap)),

159 name=_bearingTo2.__name__)

160

161

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

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

164 lat2 - lat1)} between two points.

165

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

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

168

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

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

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

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

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

174 mean latitude (C{bool}).

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

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

177

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

179

180 @note: Courtesy of Martin Schultz.

181

182 @see: U{Local, flat earth approximation

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

184 '''

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

186 if adjust: # scale delta lon

187 d_lon *= _scale_deg(lat1, lat2)

188 return atan2b(d_lon, lat2 - lat1)

189

190

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

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

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

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

195

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

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

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

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

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

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

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

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

204

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

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

207

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

209

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

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

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

213 L{Ellipsoid.distance2}.

214 '''

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

216

217

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

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

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

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

222

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

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

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

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

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

228

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

230

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

232

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

234 L{cosineLaw_}, L{equirectangular_}, L{euclidean_}, L{flatLocal_}/L{hubeny_},

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

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

237 AndoyerLambert.php>}.

238 '''

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

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

241 E = _ellipsoidal(datum, cosineAndoyerLambert_)

242 if E.f: # ellipsoidal

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

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

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

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

247 if r:

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

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

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

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

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

253 return r

254

255

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

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

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

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

260

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

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

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

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

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

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

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

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

269

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

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

272

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

274

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

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

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

278 L{Ellipsoid.distance2}.

279 '''

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

281

282

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

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

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

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

287 formula.

288

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

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

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

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

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

294

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

296

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

298

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

300 L{cosineLaw_}, L{equirectangular_}, L{euclidean_}, L{flatLocal_}/L{hubeny_},

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

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

303 Distance/ForsytheCorrection.php>}.

304 '''

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

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

307 E = _ellipsoidal(datum, cosineForsytheAndoyerLambert_)

308 if E.f: # ellipsoidal

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

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

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

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

313 x = s + t

314 y = s - t

315

316 s = 8 * r**2 / sr

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

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

319 b = -2 * d

320 e = 30 * s2r

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

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

323

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

325 return r

326

327

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

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

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

331

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

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

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

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

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

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

338 L{a_f2Tuple}) to use.

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

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

341

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

343 ellipsoid or datum axes).

344

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

346

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

348 L{cosineForsytheAndoyerLambert}, L{equirectangular}, L{euclidean},

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

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

351

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

353 '''

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

355

356

357 def cosineLaw_(phi2, phi1, lam21):

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

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

360

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

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

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

364

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

366

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

368 L{cosineForsytheAndoyerLambert_}, L{equirectangular_},

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

370 L{haversine_}, L{thomas_} and L{vincentys_}.

371

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

373 '''

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

375

376

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

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

379 '''

380 if wrap:

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

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

383 else: # for backward compaibility

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

385

386

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

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

389 '''

390 E = _ellipsoidal(earth, func_)

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

392 return r * E.a

393

394

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

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

397 '''

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

399 if radius is not R_M:

400 _, lat1, _, lat2, _ = wrap_lls

401 radius = _mean_radius(radius, lat1, lat2)

402 return r * radius

403

404

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

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

407 '''

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

409 if radius:

410 _, lat1, _, lat2, _ = wrap_lls

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

412 return r

413

414

415 def _ellipsoidal(earth, where):

416 '''(INTERNAL) Helper for distances.

417 '''

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

419 earth if isinstance(earth, Ellipsoid) else

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

421 _ellipsoidal_datum(earth, name=where.__name__)).ellipsoid)

422

423

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

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

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

427

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

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

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

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

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

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

434 L{a_f2Tuple}).

435 @kwarg adjust_limit_wrap: Optional keyword arguments for

436 function L{equirectangular_}.

437

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

439 the ellipsoid or datum axes).

440

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

442

443 @see: Function L{equirectangular_} for more details, the

444 available B{C{options}}, errors, restrictions and other,

445 approximate or accurate distance functions.

446 '''

447 d = sqrt(equirectangular_(Lat(lat1=lat1), Lon(lon1=lon1),

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

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

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

451

452

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

454 '''(INTERNAL) Helper for the L{frechet._FrecherMeterRadians}

455 and L{hausdorff._HausdorffMeterRedians} classes.

456 '''

457 return equirectangular_(lat1, lon1, lat2, lon2, **adjust_limit_wrap).distance2 * _D2_R2

458

459

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

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

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

463

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

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

466

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

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

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

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

471 @kwarg adjust: Adjust the wrapped, unrolled longitudinal delta

472 by the cosine of the mean latitude (C{bool}).

473 @kwarg limit: Optional limit for lat- and longitudinal deltas

474 (C{degrees}) or C{None} or C{0} for unlimited.

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

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

477

478 @return: A L{Distance4Tuple}C{(distance2, delta_lat, delta_lon,

479 unroll_lon2)} in C{degrees squared}.

480

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

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

483 set to C{True}.

484

485 @see: U{Local, flat earth approximation

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

487 L{equirectangular}, L{cosineAndoyerLambert},

488 L{cosineForsytheAndoyerLambert}, L{cosineLaw}, L{euclidean},

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

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

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

492 '''

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

494 d_lat = lat2 - lat1

495

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

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

498 if d > limit:

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

500 s = unstr(equirectangular_, lat1, lon1, lat2, lon2,

501 limit=limit, wrap=wrap)

502 raise LimitError(s, txt=t)

503

504 if adjust: # scale delta lon

505 d_lon *= _scale_deg(lat1, lat2)

506

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

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

509

510

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

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

513

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

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

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

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

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

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

520 L{a_f2Tuple}) to use.

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

522 the mean latitude (C{bool}).

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

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

525

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

527 ellipsoid or datum axes).

528

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

530

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

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

533 L{euclidean_}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

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

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

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

537 '''

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

539

540

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

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

543

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

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

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

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

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

549

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

551

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

553 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_}, L{equirectangular_},

554 L{flatLocal_}/L{hubeny_}, L{flatPolar_}, L{haversine_}, L{thomas_}

555 and L{vincentys_}.

556 '''

557 if adjust:

558 lam21 *= _scale_rad(phi2, phi1)

559 return euclid(phi2 - phi1, lam21)

560

561

562 def excessAbc_(A, b, c):

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

564 and the included (small) angle.

565

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

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

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

569

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

571

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

573

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

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

576 '''

577 A = Radians_(A=A)

578 b = Radians_(b=b) * _0_5

579 c = Radians_(c=c) * _0_5

580

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

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

583

584

585 def excessCagnoli_(a, b, c):

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

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

588

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

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

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

592

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

594

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

596

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

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

599 '''

600 a = Radians_(a=a)

601 b = Radians_(b=b)

602 c = Radians_(c=c)

603

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

605 r = sin(s) * sin(s - a) * sin(s - b) * sin(s - c)

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

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

608 return Radians(Cagnoli=r * _2_0)

609

610

611 def excessGirard_(A, B, C):

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

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

614

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

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

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

618

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

620

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

622

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

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

625 '''

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

627 Radians_(B=B),

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

629

630

631 def excessLHuilier_(a, b, c):

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

633 <https://MathWorld.Wolfram.com/LHuiliersTheorem.html>} Theorem.

634

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

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

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

638

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

640

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

642

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

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

645 '''

646 a = Radians_(a=a)

647 b = Radians_(b=b)

648 c = Radians_(c=c)

649

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

651 r = tan_2(s) * tan_2(s - a) * tan_2(s - b) * tan_2(s - c)

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

653 return Radians(LHuilier=r * _4_0)

654

655

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

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

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

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

660 method.

661

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

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

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

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

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

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

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

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

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

671

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

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

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

675

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

677

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

679

680 @raise ValueError: Semi-circular longitudinal delta.

681

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

683 '''

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

685

686

687 def excessKarney_(phi2, phi1, lam21):

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

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

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

691 method.

692

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

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

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

696

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

698

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

700

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

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

703 '''

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

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

706 #

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

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

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

710 #

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

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

713 t2 = tan_2(phi2)

714 t1 = tan_2(phi1)

715 t = tan_2(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{equirectangular_}, L{euclidean_}, L{haversine_}, L{thomas_}

866 and L{vincentys_} and 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{equirectangular_}, L{euclidean_}, L{flatLocal_}/L{hubeny_},

920 L{haversine_}, 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(inst, los, earth, **kwds):

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

938 '''

939 if earth is not None:

940 earth = _spherical_datum(earth, name=hartzell.__name__)

941 inst = inst.toDatum(earth)

942 h = inst.height

943 if h > 0: # EPS0

944 r = hartzell(inst, los=los, earth=earth or inst.datum, **kwds)

945 elif h < 0: # EPS0

946 raise IntersectionError(pov=inst, los=los, height=h, txt=_inside_)

947 else:

948 r = inst

949 return r

950

951

952 def hartzell(pov, los=None, earth=_WGS84, name=NN, **LatLon_and_kwds):

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

954 from a Point-Of-View in space.

955

956 @arg pov: Point-Of-View outside the earth (C{Cartesian}, L{Ecef9Tuple}

957 C{LatLon} or L{Vector3d}).

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

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

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

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

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

963 @kwarg LatLon_and_kwds: Optional C{LatLon} class for the intersection

964 point plus C{LatLon} keyword arguments, include

965 B{C{datum}} if different from B{C{earth}}.

966

967 @return: The intersection point (L{Vector3d}, the C{Cartesian type} of

968 B{C{pov}} or the given C{B{LatLon}_and_kwds}) with C{.heigth}

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

970

971 @raise IntersectionError: Null B{C{pov}} or B{C{los}} vector, B{C{pov}}

972 is inside the earth or B{C{los}} points outside

973 the earth or points in an opposite direction.

974

975 @raise TypeError: Invalid B{C{pov}}, B{C{los}} or B{C{earth}}.

976

977 @see: Function L{pygeodesy.hartzell4}, L{pygeodesy.tyr3d} for B{C{los}},

978 methods L{Ellipsoid.hartzell4}, C{Cartesian.hartzell}, C{LatLon.hartzell}

979 and U{I{Satellite Line-of-Sight Intersection with Earth}<https://

980 StephenHartzell.Medium.com/satellite-line-of-sight-intersection-with-earth-d786b4a6a9b6>}.

981 '''

982 n = hartzell.__name__

983 D = earth if isinstance(earth, Datum) else \

984 _spherical_datum(earth, name=n)

985 try:

986 r, h = _MODS.triaxials._hartzell3d2(pov, los, D.ellipsoid._triaxial)

987 except Exception as x:

988 raise IntersectionError(pov=pov, los=los, earth=earth, cause=x)

989

990 r = _xnamed(r, name or n)

991 C = _MODS.cartesianBase.CartesianBase

992 if LatLon_and_kwds:

993 c = C(r, datum=D, name=r.name)

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

995 elif isinstance(r, C):

996 r.height = h

997 return r

998

999

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

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

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

1003 formula.

1004

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

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

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

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

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

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

1011 L{a_f2Tuple}) to use.

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

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

1014

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

1016

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

1018

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

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

1021 L{cosineLaw}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

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

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

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

1025

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

1027 '''

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

1029

1030

1031 def haversine_(phi2, phi1, lam21):

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

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

1034 formula.

1035

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

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

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

1039

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

1041

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

1043 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

1044 L{equirectangular_}, L{euclidean_}, L{flatLocal_}/L{hubeny_},

1045 L{flatPolar_}, L{thomas_} and L{vincentys_}.

1046

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

1048 '''

1049 def _hsin(rad):

1050 return sin(rad * _0_5)**2

1051

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

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

1054

1055

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

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

1058 traveling along a straight line at a given tilt.

1059

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

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

1062 B{C{radius}}).

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

1064

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

1066

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

1068

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

1070 (U{Shapiro et al. 2009, JTECH

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

1072 and U{Potvin et al. 2012, JTECH

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

1074 '''

1075 r = h = Radius(radius)

1076 d = fabs(Distance(distance))

1077 if d > h:

1078 d, h = h, d

1079

1080 if d > EPS0: # and h > EPS0

1081 d = d / h # /= h chokes PyChecker

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

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

1084 if s > 0:

1085 return h * sqrt(s) - r

1086

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

1088

1089

1090 def heightOrthometric(h_ll, N):

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

1092

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

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

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

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

1097

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

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

1100

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

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

1103 6 and module L{pygeodesy.geoids}.

1104 '''

1105 h = h_ll if isscalar(h_ll) else _xattr(h_ll, height=_xattr(h_ll, h=0))

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

1107

1108

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

1110 '''Determine the distance to the horizon from a given altitude

1111 above the (spherical) earth.

1112

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

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

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

1116

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

1118

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

1120

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

1122 '''

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

1124 if min(h, r) < 0:

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

1126

1127 if refraction:

1128 d2 = 2.415750694528 * h * r # 2.0 / 0.8279

1129 else:

1130 d2 = h * fsumf_(r, r, h)

1131 return sqrt0(d2)

1132

1133

1134 class _idllmn6(object): # see also .geodesicw._wargs, .vector2d._numpy

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

1136 '''

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

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

1139 try:

1140 if wrap:

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

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

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

1144 n = (intersections2 if s else intersection2).__name__

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

1146 d, m = None, _MODS.vector3d

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

1148 elif isscalar(datum) and datum < 0 and not s:

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

1150 m = _MODS.sphericalNvector

1151 _i = m.intersection

1152 else:

1153 d = _spherical_datum(datum, name=n)

1154 if d.isSpherical:

1155 m = _MODS.sphericalTrigonometry

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

1157 elif d.isEllipsoidal:

1158 try:

1159 if d.ellipsoid.geodesic:

1160 pass

1161 m = _MODS.ellipsoidalKarney

1162 except ImportError:

1163 m = _MODS.ellipsoidalExact

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

1165 else:

1166 raise _TypeError(datum=datum)

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

1168

1169 except (TypeError, ValueError) as x:

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

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

1172

1173_idllmn6 = _idllmn6() # PYCHOK singleton

1174

1175

1176 def intersection2(lat1, lon1, bearing1,

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

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

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

1180

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

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

1183

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

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

1186 in C{meter} or ...

1187

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

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

1190

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

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

1193 is installed, otherwise ...

1194

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

1196

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

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

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

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

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

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

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

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

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

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

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

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

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

1210

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

1212 longitude of the intersection point.

1213

1214 @raise IntersectionError: Ambiguous or infinite intersection

1215 or colinear, parallel or otherwise

1216 non-intersecting lines.

1217

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

1219

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

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

1222

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

1224

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

1226 '''

1227 b1 = Bearing(bearing1=bearing1)

1228 b2 = Bearing(bearing2=bearing2)

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

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

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

1232 if d is None:

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

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

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

1236

1237 else:

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

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

1240 if isinstance(t, Intersection3Tuple): # ellipsoidal

1241 t, _, _ = t

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

1243 return t

1244

1245

1246 def intersections2(lat1, lon1, radius1,

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

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

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

1250

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

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

1253

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

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

1256 in C{meter} or ...

1257

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

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

1260 is installed, otherwise ...

1261

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

1263

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

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

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

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

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

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

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

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

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

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

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

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

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

1277

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

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

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

1281

1282 @raise IntersectionError: Concentric, antipodal, invalid or

1283 non-intersecting circles or no

1284 convergence.

1285

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

1287

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

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

1290 '''

1291 r1 = Radius_(radius1=radius1)

1292 r2 = Radius_(radius2=radius2)

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

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

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

1296 if d is None:

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

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

1299

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

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

1302

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

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

1305 Vector=_V2T)

1306 else:

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

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

1309

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

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

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

1313 return t

1314

1315

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

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

1318 opposite sides of the earth.

1319

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

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

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

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

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

1325

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

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

1328

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

1330 '''

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

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

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

1334

1335

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

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

1338 opposite sides of the earth.

1339

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

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

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

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

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

1345

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

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

1348

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

1350 '''

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

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

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

1354

1355

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

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

1358 '''

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

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

1361

1362

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

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

1365 '''

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

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

1368

1369

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

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

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

1373

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

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

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

1377

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

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

1380

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

1382 '''

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

1384

1385

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

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

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

1389

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

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

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

1393

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

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

1396

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

1398 '''

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

1400

1401

1402 def latlon2n_xyz(lat, lon, name=NN):

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

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

1405

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

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

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

1409

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

1411

1412 @see: Function L{philam2n_xyz}.

1413

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

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

1416 '''

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

1418

1419

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

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

1422 '''

1423 if fabs(b) > n:

1424 b = remainder(b, n2)

1425 if fabs(a) > n_2:

1426 r = remainder(a, n)

1427 if r != a:

1428 a = -r

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

1430 return float0_(a, b)

1431

1432

1433 def normal(lat, lon, name=NN):

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

1435

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

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

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

1439

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

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

1442

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

1444 '''

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

1446 name=name or normal.__name__)

1447

1448

1449 def normal_(phi, lam, name=NN):

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

1451

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

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

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

1455

1456 @return: L{PhiLam2Tuple}C{(phi, lam)} with C{abs(phi) <= PI/2}

1457 and C{abs(lam) <= PI}.

1458

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

1460 '''

1461 return PhiLam2Tuple(*_normal2(phi, lam, PI_2, PI, PI2),

1462 name=name or normal_.__name__)

1463

1464

1465 def _2n_xyz(name, sa, ca, sb, cb):

1466 '''(INTERNAL) Helper for C{latlon2n_xyz} and C{philam2n_xyz}.

1467 '''

1468 # Kenneth Gade eqn 3, but using right-handed

1469 # vector x -> 0°E,0°N, y -> 90°E,0°N, z -> 90°N

1470 return Vector3Tuple(ca * cb, ca * sb, sa, name=name)

1471

1472

1473 def n_xyz2latlon(x, y, z, name=NN):

1474 '''Convert C{n-vector} components to lat- and longitude in C{degrees}.

1475

1476 @arg x: X component (C{scalar}).

1477 @arg y: Y component (C{scalar}).

1478 @arg z: Z component (C{scalar}).

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

1480

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

1482

1483 @see: Function L{n_xyz2philam}.

1484 '''

1485 return LatLon2Tuple(atan2d(z, hypot(x, y)), atan2d(y, x), name=name)

1486

1487

1488 def n_xyz2philam(x, y, z, name=NN):

1489 '''Convert C{n-vector} components to lat- and longitude in C{radians}.

1490

1491 @arg x: X component (C{scalar}).

1492 @arg y: Y component (C{scalar}).

1493 @arg z: Z component (C{scalar}).

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

1495

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

1497

1498 @see: Function L{n_xyz2latlon}.

1499 '''

1500 return PhiLam2Tuple(atan2(z, hypot(x, y)), atan2(y, x), name=name)

1501

1502

1503 def _opposes(d, m, n, n2):

1504 '''(INTERNAL) Helper for C{opposing} and C{opposing_}.

1505 '''

1506 d = d % n2 # -20 % 360 == 340, -1 % PI2 == PI2 - 1

1507 return False if d < m or d > (n2 - m) else (

1508 True if (n - m) < d < (n + m) else None)

1509

1510

1511 def opposing(bearing1, bearing2, margin=_90_0):

1512 '''Compare the direction of two bearings given in C{degrees}.

1513

1514 @arg bearing1: First bearing (compass C{degrees}).

1515 @arg bearing2: Second bearing (compass C{degrees}).

1516 @kwarg margin: Optional, interior angle bracket (C{degrees}).

1517

1518 @return: C{True} if both bearings point in opposite, C{False} if

1519 in similar or C{None} if in I{perpendicular} directions.

1520

1521 @see: Function L{opposing_}.

1522 '''

1523 m = Degrees_(margin=margin, low=EPS0, high=_90_0)

1524 return _opposes(bearing2 - bearing1, m, _180_0, _360_0)

1525

1526

1527 def opposing_(radians1, radians2, margin=PI_2):

1528 '''Compare the direction of two bearings given in C{radians}.

1529

1530 @arg radians1: First bearing (C{radians}).

1531 @arg radians2: Second bearing (C{radians}).

1532 @kwarg margin: Optional, interior angle bracket (C{radians}).

1533

1534 @return: C{True} if both bearings point in opposite, C{False} if

1535 in similar or C{None} if in perpendicular directions.

1536

1537 @see: Function L{opposing}.

1538 '''

1539 m = Radians_(margin=margin, low=EPS0, high=PI_2)

1540 return _opposes(radians2 - radians1, m, PI, PI2)

1541

1542

1543 def philam2n_xyz(phi, lam, name=NN):

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

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

1546

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

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

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

1550

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

1552

1553 @see: Function L{latlon2n_xyz}.

1554

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

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

1557 '''

1558 return _2n_xyz(name, *sincos2_(phi, lam))

1559

1560

1561 def _radical2(d, r1, r2): # in .ellipsoidalBaseDI, .sphericalTrigonometry, .vector3d

1562 # (INTERNAL) See C{radical2} below

1563 # assert d > EPS0

1564 r = fsumf_(_1_0, (r1 / d)**2, -(r2 / d)**2) * _0_5

1565 return Radical2Tuple(max(_0_0, min(_1_0, r)), r * d)

1566

1567

1568 def radical2(distance, radius1, radius2):

1569 '''Compute the I{radical ratio} and I{radical line} of two

1570 U{intersecting circles<https://MathWorld.Wolfram.com/

1571 Circle-CircleIntersection.html>}.

1572

1573 The I{radical line} is perpendicular to the axis thru the

1574 centers of the circles at C{(0, 0)} and C{(B{distance}, 0)}.

1575

1576 @arg distance: Distance between the circle centers (C{scalar}).

1577 @arg radius1: Radius of the first circle (C{scalar}).

1578 @arg radius2: Radius of the second circle (C{scalar}).

1579

1580 @return: A L{Radical2Tuple}C{(ratio, xline)} where C{0.0 <=

1581 ratio <= 1.0} and C{xline} is along the B{C{distance}}.

1582

1583 @raise IntersectionError: The B{C{distance}} exceeds the sum

1584 of B{C{radius1}} and B{C{radius2}}.

1585

1586 @raise UnitError: Invalid B{C{distance}}, B{C{radius1}} or

1587 B{C{radius2}}.

1588

1589 @see: U{Circle-Circle Intersection

1590 <https://MathWorld.Wolfram.com/Circle-CircleIntersection.html>}.

1591 '''

1592 d = Distance_(distance, low=_0_0)

1593 r1 = Radius_(radius1=radius1)

1594 r2 = Radius_(radius2=radius2)

1595 if d > (r1 + r2):

1596 raise IntersectionError(distance=d, radius1=r1, radius2=r2,

1597 txt=_too_(_distant_))

1598 return _radical2(d, r1, r2) if d > EPS0 else \

1599 Radical2Tuple(_0_5, _0_0)

1600

1601

1602 class Radical2Tuple(_NamedTuple):

1603 '''2-Tuple C{(ratio, xline)} of the I{radical} C{ratio} and

1604 I{radical} C{xline}, both C{scalar} and C{0.0 <= ratio <= 1.0}

1605 '''

1606 _Names_ = (_ratio_, _xline_)

1607 _Units_ = ( Scalar, Scalar)

1608

1609

1610 def _radistance(inst):

1611 '''(INTERNAL) Helper for the L{frechet._FrecherMeterRadians}

1612 and L{hausdorff._HausdorffMeterRedians} classes.

1613 '''

1614 kwds_ = _xkwds(inst._kwds, wrap=False)

1615 wrap_ = _xkwds_pop(kwds_, wrap=False)

1616 func_ = inst._func_

1617 try: # calling lower-overhead C{func_}

1618 func_(0, _0_25, _0_5, **kwds_)

1619 wrap_ = _Wrap._philamop(wrap_)

1620 except TypeError:

1621 return inst.distance

1622

1623 def _philam(p):

1624 try:

1625 return p.phi, p.lam

1626 except AttributeError: # no .phi or .lam

1627 return radians(p.lat), radians(p.lon)

1628

1629 def _func_wrap(point1, point2):

1630 phi1, lam1 = wrap_(*_philam(point1))

1631 phi2, lam2 = wrap_(*_philam(point2))

1632 return func_(phi2, phi1, lam2 - lam1, **kwds_)

1633

1634 inst._units = inst._units_

1635 return _func_wrap

1636

1637

1638 def _scale_deg(lat1, lat2): # degrees

1639 # scale factor cos(mean of lats) for delta lon

1640 m = fabs(lat1 + lat2) * _0_5

1641 return cos(radians(m)) if m < 90 else _0_0

1642

1643

1644 def _scale_rad(phi1, phi2): # radians, by .frechet, .hausdorff, .heights

1645 # scale factor cos(mean of phis) for delta lam

1646 m = fabs(phi1 + phi2) * _0_5

1647 return cos(m) if m < PI_2 else _0_0

1648

1649

1650 def _sincosa6(phi2, phi1, lam21): # [4] in cosineLaw

1651 '''(INTERNAL) C{sin}es, C{cos}ines and C{acos}ine.

1652 '''

1653 s2, c2, s1, c1, _, c21 = sincos2_(phi2, phi1, lam21)

1654 return s2, c2, s1, c1, acos1(s1 * s2 + c1 * c2 * c21), c21

1655

1656

1657 def thomas(lat1, lon1, lat2, lon2, datum=_WGS84, wrap=False):

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

1659 U{Thomas'<https://apps.DTIC.mil/dtic/tr/fulltext/u2/703541.pdf>}

1660 formula.

1661

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

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

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

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

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

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

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

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

1670

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

1672 ellipsoid axes).

1673

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

1675

1676 @see: Functions L{thomas_}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

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

1678 L{flatPolar}, L{haversine}, L{vincentys} and method L{Ellipsoid.distance2}.

1679 '''

1680 return _dE(thomas_, datum, wrap, lat1, lon1, lat2, lon2)

1681

1682

1683 def thomas_(phi2, phi1, lam21, datum=_WGS84):

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

1685 U{Thomas'<https://apps.DTIC.mil/dtic/tr/fulltext/u2/703541.pdf>}

1686 formula.

1687

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

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

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

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

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

1693

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

1695

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

1697

1698 @see: Functions L{thomas}, L{cosineAndoyerLambert_},

1699 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

1700 L{equirectangular_}, L{euclidean_}, L{flatLocal_}/L{hubeny_},

1701 L{flatPolar_}, L{haversine_} and L{vincentys_} and U{Geodesy-PHP

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

1703 Distance/ThomasFormula.php>}.

1704 '''

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

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

1707 E = _ellipsoidal(datum, thomas_)

1708 if E.f:

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

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

1711

1712 j = (r2 + r1) * _0_5

1713 k = (r2 - r1) * _0_5

1714 sj, cj, sk, ck, h, _ = sincos2_(j, k, lam21 * _0_5)

1715

1716 h = fsumf_(sk**2, (ck * h)**2, -(sj * h)**2)

1717 u = _1_0 - h

1718 if isnon0(u) and isnon0(h):

1719 r = atan(sqrt0(h / u)) * 2 # == acos(1 - 2 * h)

1720 sr, cr = sincos2(r)

1721 if isnon0(sr):

1722 u = 2 * (sj * ck)**2 / u

1723 h = 2 * (sk * cj)**2 / h

1724 x = u + h

1725 y = u - h

1726

1727 s = r / sr

1728 e = 4 * s**2

1729 d = 2 * cr

1730 a = e * d

1731 b = 2 * r

1732 c = s - (a - d) * _0_5

1733 f = E.f * _0_25

1734

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

1736 r -= fsumf_(s * x, -y, -t * f * _0_25) * f * sr

1737 return r

1738

1739

1740 def vincentys(lat1, lon1, lat2, lon2, radius=R_M, wrap=False):

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

1742 U{Vincenty's<https://WikiPedia.org/wiki/Great-circle_distance>}

1743 spherical formula.

1744

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

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

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

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

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

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

1751 L{a_f2Tuple}) to use.

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

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

1754

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

1756

1757 @raise UnitError: Invalid B{C{radius}}.

1758

1759 @see: Functions L{vincentys_}, L{cosineAndoyerLambert},

1760 L{cosineForsytheAndoyerLambert},L{cosineLaw}, L{equirectangular},

1761 L{euclidean}, L{flatLocal}/L{hubeny}, L{flatPolar},

1762 L{haversine} and L{thomas} and methods L{Ellipsoid.distance2},

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

1764

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

1766 '''

1767 return _dS(vincentys_, radius, wrap, lat1, lon1, lat2, lon2)

1768

1769

1770 def vincentys_(phi2, phi1, lam21):

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

1772 U{Vincenty's<https://WikiPedia.org/wiki/Great-circle_distance>}

1773 spherical formula.

1774

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

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

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

1778

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

1780

1781 @see: Functions L{vincentys}, L{cosineAndoyerLambert_},

1782 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

1783 L{equirectangular_}, L{euclidean_}, L{flatLocal_}/L{hubeny_},

1784 L{flatPolar_}, L{haversine_} and L{thomas_}.

1785

1786 @note: Functions L{vincentys_}, L{haversine_} and L{cosineLaw_}

1787 produce equivalent results, but L{vincentys_} is suitable

1788 for antipodal points and slightly more expensive (M{3 cos,

1789 3 sin, 1 hypot, 1 atan2, 6 mul, 2 add}) than L{haversine_}

1790 (M{2 cos, 2 sin, 2 sqrt, 1 atan2, 5 mul, 1 add}) and

1791 L{cosineLaw_} (M{3 cos, 3 sin, 1 acos, 3 mul, 1 add}).

1792 '''

1793 s1, c1, s2, c2, s21, c21 = sincos2_(phi1, phi2, lam21)

1794

1795 c = c2 * c21

1796 x = s1 * s2 + c1 * c

1797 y = c1 * s2 - s1 * c

1798 return atan2(hypot(c2 * s21, y), x)

1799

1800# **) MIT License

1801#

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

1803#

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

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

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

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

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

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

1810#

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

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

1813#

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

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

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

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

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

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

1820# OTHER DEALINGS IN THE SOFTWARE.