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.constants import EPS, EPS0, EPS1, PI, PI2, PI3, PI_2, R_M, \

11 _umod_PI2, float0_, isnon0, remainder, \

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

13 _4_0, _32_0, _90_0, _180_0, _360_0

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

15 _mean_radius, _spherical_datum, _WGS84

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

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

18 _TypeError, _ValueError, \

19 _xError, _xkwds, _xkwds_pop

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

21 from pygeodesy.fsums import fsumf_, isscalar

22 from pygeodesy.interns import NN, _delta_, _distant_, _SPACE_, _too_

23 from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS

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

25 from pygeodesy.namedTuples import Bearing2Tuple, Distance4Tuple, \

26 Intersection3Tuple, LatLon2Tuple, \

27 PhiLam2Tuple, Vector3Tuple

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

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

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

31 Radius, Radius_, Scalar, _100km

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

33 tan_2, sincos2, sincos2_, sincos2d_, _Wrap

34

35 from contextlib import contextmanager

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

37

38__all__ = _ALL_LAZY.formy

39__version__ = '23.08.11'

40

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

42_EWGS84 = _WGS84.ellipsoid

43_ratio_ = 'ratio'

44_xline_ = 'xline'

45

46

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

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

49 '''

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

51 if r == a:

52 r = -r

53 b += n

54 if fabs(b) > n:

55 b = remainder(b, n2)

56 return float0_(r, b)

57

58

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

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

61 to a given point in C{degrees}.

62

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

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

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

66

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

68

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

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

71 '''

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

73

74

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

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

77 to a given point in C{radians}.

78

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

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

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

82

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

84

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

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

87 '''

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

89

90

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

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

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

94

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

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

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

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

99 @kwarg final_wrap: Optional keyword arguments for function

100 L{pygeodesy.bearing_}.

101

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

103 zero if start and end point coincide.

104 '''

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

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

107 return degrees(r)

108

109

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

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

112 between a (spherical) start and end point.

113

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

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

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

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

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

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

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

121

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

123 and end point coincide.

124

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

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

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

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

129 '''

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

131 if final: # swap plus PI

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

133 r = PI3

134 else:

135 r = PI2

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

137

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

139 y = sdb * ca2

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

141

142

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

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

145 '''

146 try: # for LatLon_ and ellipsoidal LatLon

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

148 except AttributeError:

149 pass

150 # XXX spherical version, OK for ellipsoidal ispolar?

151 a1, b1 = p1.philam

152 a2, b2 = p2.philam

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

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

155 name=_bearingTo2.__name__)

156

157

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

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

160 lat2 - lat1)} between two points.

161

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

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

164

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

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

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

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

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

170 mean latitude (C{bool}).

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

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

173

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

175

176 @note: Courtesy of Martin Schultz.

177

178 @see: U{Local, flat earth approximation

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

180 '''

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

182 if adjust: # scale delta lon

183 d_lon *= _scale_deg(lat1, lat2)

184 return atan2b(d_lon, lat2 - lat1)

185

186

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

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

189 U{Andoyer-Lambert correction<https://NavLib.net/wp-content/uploads/2013/10/

190 admiralty-manual-of-navigation-vol-1-1964-english501c.pdf>} of the U{Law of

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

192

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

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

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

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

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

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

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

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

201

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

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

204

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

206

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

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

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

210 L{Ellipsoid.distance2}.

211 '''

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

213

214

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

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

217 U{Andoyer-Lambert correction<https://NavLib.net/wp-content/uploads/2013/10/

218 admiralty-manual-of-navigation-vol-1-1964-english501c.pdf>} of the U{Law of

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

220

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

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

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

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

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

226

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

228

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

230

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

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

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

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

235 AndoyerLambert.php>}.

236 '''

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

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

239 E = _ellipsoidal(datum, cosineAndoyerLambert_)

240 if E.f: # ellipsoidal

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

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

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

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

245 if r:

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

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

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

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

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

251 return r

252

253

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

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

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

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

258 formula.

259

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

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

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

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

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

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

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

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

268

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

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

271

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

273

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

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

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

277 L{Ellipsoid.distance2}.

278 '''

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

280

281

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

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

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

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

286 formula.

287

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

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

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

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

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

293

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

295

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

297

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

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

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

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

302 Distance/ForsytheCorrection.php>}.

303 '''

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

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

306 E = _ellipsoidal(datum, cosineForsytheAndoyerLambert_)

307 if E.f: # ellipsoidal

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

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

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

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

312 x = s + t

313 y = s - t

314

315 s = 8 * r**2 / sr

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

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

318 b = -2 * d

319 e = 30 * s2r

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

321

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

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

324 return r

325

326

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

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

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

330 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

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

360 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{equirectangular_},

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

371 L{haversine_}, 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.__name__)).ellipsoid)

423

424

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

426 '''Compute the distance between two points using

427 the U{Equirectangular Approximation / Projection

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

429

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

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

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

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

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

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

436 L{a_f2Tuple}).

437 @kwarg adjust_limit_wrap: Optional keyword arguments for

438 function L{equirectangular_}.

439

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

441 the ellipsoid or datum axes).

442

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

444

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

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

447 approximate or accurate distance functions.

448 '''

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

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

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

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

453

454

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

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

457 and L{hausdorff._HausdorffMeterRedians} classes.

458 '''

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

460

461

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

463 '''Compute the distance between two points using the U{Equirectangular

464 Approximation / Projection

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

466

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

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

469

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

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

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

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

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

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

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

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

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

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

480

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

482 unroll_lon2)} in C{degrees squared}.

483

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

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

486 set to C{True}.

487

488 @see: U{Local, flat earth approximation

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

490 L{equirectangular}, L{cosineAndoyerLambert},

491 L{cosineForsytheAndoyerLambert}, L{cosineLaw}, L{euclidean},

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

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

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

495 '''

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

497 d_lat = lat2 - lat1

498

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

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

501 if d > limit:

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

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

504 limit=limit, wrap=wrap)

505 raise LimitError(s, txt=t)

506

507 if adjust: # scale delta lon

508 d_lon *= _scale_deg(lat1, lat2)

509

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

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

512

513

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

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

516

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

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

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

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

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

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

523 L{a_f2Tuple}) to use.

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

525 the mean latitude (C{bool}).

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

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

528

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

530 ellipsoid or datum axes).

531

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

533

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

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

536 L{euclidean_}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

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

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

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

540 '''

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

542

543

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

545 '''Approximate the I{angular} C{Euclidean} distance between two

546 (spherical) points.

547

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

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

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

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

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

553

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

555

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

557 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_}, L{equirectangular_},

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

559 and L{vincentys_}.

560 '''

561 if adjust:

562 lam21 *= _scale_rad(phi2, phi1)

563 return euclid(phi2 - phi1, lam21)

564

565

566 def excessAbc_(A, b, c):

567 '''Compute the I{spherical excess} C{E} of a (spherical) triangle

568 from two sides and the included (small) angle.

569

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

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

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

573

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

575

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

577

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

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

580 '''

581 sA, cA, sb, cb, sc, cc = sincos2_(Radians_(A=A), Radians_(b=b) * _0_5,

582 Radians_(c=c) * _0_5)

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

584

585

586 def excessCagnoli_(a, b, c):

587 '''Compute the I{spherical excess} C{E} of a (spherical) triangle using

588 U{Cagnoli's<https://Zenodo.org/record/35392>} (D.34) formula.

589

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

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

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

593

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

595

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

597

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

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

600 '''

601 a = Radians_(a=a)

602 b = Radians_(b=b)

603 c = Radians_(c=c)

604

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

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

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

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

609 return Radians(Cagnoli=r * _2_0)

610

611

612 def excessGirard_(A, B, C):

613 '''Compute the I{spherical excess} C{E} of a (spherical) triangle using

614 U{Girard's<https://MathWorld.Wolfram.com/GirardsSphericalExcessFormula.html>}

615 formula.

616

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

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

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

620

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

622

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

624

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

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

627 '''

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

629 Radians_(B=B),

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

631

632

633 def excessLHuilier_(a, b, c):

634 '''Compute the I{spherical excess} C{E} of a (spherical) triangle using

635 U{L'Huilier's<https://MathWorld.Wolfram.com/LHuiliersTheorem.html>}

636 Theorem.

637

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

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

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

641

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

643

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

645

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

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

648 '''

649 a = Radians_(a=a)

650 b = Radians_(b=b)

651 c = Radians_(c=c)

652

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

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

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

656 return Radians(LHuilier=r * _4_0)

657

658

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

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

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

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

663 method.

664

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

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

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

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

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

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

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

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

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

674

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

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

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

678

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

680

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

682

683 @raise ValueError: Semi-circular longitudinal delta.

684

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

686 '''

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

688

689

690 def excessKarney_(phi2, phi1, lam21):

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

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

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

694 method.

695

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

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

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

699

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

701

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

703

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

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

706 '''

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

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

709 #

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

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

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

713 #

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

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

716 t2 = tan_2(phi2)

717 t1 = tan_2(phi1)

718 t = tan_2(lam21, lam21=None)

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

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

721

722

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

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

725#

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

727#

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

729#

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

731#

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

733#

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

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

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

737#

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

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

740#

741# = tan(lambda21 / 2) * tanh((Lambertian(phi1) +

742# Lambertian(phi2)) / 2)

743#

744# where lambda21 = lambda2 - lambda1 and lamb(x) is the Lambertian (or

745# inverse Gudermannian) function

746#

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

748#

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

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

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

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

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

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

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

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

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

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

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

760# - Charles Karney

761

762

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

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

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

766

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

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

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

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

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

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

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

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

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

776

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

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

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

780

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

782

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

784

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

786 '''

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

788

789

790 def excessQuad_(phi2, phi1, lam21):

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

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

793

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

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

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

797

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

799

800 @see: Function L{excessQuad}, U{Spherical trigonometry

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

802 '''

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

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

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

806

807

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

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

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

811 wiki/Geographical_distance#Ellipsoidal_Earth_projected_to_a_plane>}

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

813

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

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

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

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

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

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

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

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

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

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

824

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

826 ellipsoid axes).

827

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

829

830 @note: The meridional and prime_vertical radii of curvature

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

832

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

834 L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

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

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

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

838 '''

839 E = _ellipsoidal(datum, flatLocal)

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

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

842

843 hubeny = flatLocal # PYCHOK for Karl Hubeny

844

845

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

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

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

849 wiki/Geographical_distance#Ellipsoidal_Earth_projected_to_a_plane>}

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

851

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

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

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

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

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

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

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

859

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

861

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

863

864 @note: The meridional and prime_vertical radii of curvature

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

866

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

868 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_}, L{flatPolar_},

869 L{equirectangular_}, L{euclidean_}, L{haversine_}, L{thomas_}

870 and L{vincentys_} and U{local, flat earth approximation

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

872 '''

873 E = _ellipsoidal(datum, flatLocal_)

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

875

876 hubeny_ = flatLocal_ # PYCHOK for Karl Hubeny

877

878

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

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

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

882 Geographical_distance#Polar_coordinate_flat-Earth_formula>}

883 formula.

884

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

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

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

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

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

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

891 L{a_f2Tuple}) to use.

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

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

894

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

896 ellipsoid or datum axes).

897

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

899

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

901 L{cosineForsytheAndoyerLambert},L{cosineLaw},

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

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

904 L{vincentys}.

905 '''

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

907

908

909 def flatPolar_(phi2, phi1, lam21):

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

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

912 Geographical_distance#Polar_coordinate_flat-Earth_formula>}

913 formula.

914

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

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

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

918

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

920

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

922 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

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

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

925 '''

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

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

928 if a < b:

929 a, b = b, a

930 if a < EPS0:

931 a = _0_0

932 elif b > 0:

933 b = b / a # /= chokes PyChecker

934 c = b * cos(lam21) * _2_0

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

936 a *= sqrt0(c)

937 return a

938

939

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

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

942 from a Point-Of-View in space.

943

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

945 or L{Vector3d}).

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

947 C{None} to point to the earth' center.

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

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

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

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

952 point plus C{LatLon} keyword arguments, include

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

954

955 @return: The earth intersection (L{Vector3d}, C{Cartesian type} of

956 B{C{pov}} or B{C{LatLon}}).

957

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

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

960 the earth or points in an opposite direction.

961

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

963

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

965 method L{Ellipsoid.hartzell4} and U{I{Satellite Line-of-Sight

966 Intersection with Earth}<https://StephenHartzell.Medium.com/

967 satellite-line-of-sight-intersection-with-earth-d786b4a6a9b6>}.

968 '''

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

970 _spherical_datum(earth, name=hartzell.__name__)

971 try:

972 r, _ = _MODS.triaxials._hartzell3d2(pov, los, D.ellipsoid._triaxial)

973 except Exception as x:

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

975

976# else:

977# E = D.ellipsoid

978# # Triaxial(a, b, c) == (E.a, E.a, E.b)

979#

980# def _Error(txt):

981# return IntersectionError(pov=pov, los=los, earth=earth, txt=txt)

982#

983# a2 = b2 = E.a2 # earth' x, y, ...

984# c2 = E.b2 # ... z semi-axis squared

985# q2 = E.b2_a2 # == c2 / a2

986# bc = E.a * E.b # == b * c

987#

988# V3 = _MODS.vector3d._otherV3d

989# p3 = V3(pov=pov)

990# u3 = V3(los=los) if los else p3.negate()

991# u3 = u3.unit() # unit vector, opposing signs

992#

993# x2, y2, z2 = p3.x2y2z2 # p3.times_(p3).xyz

994# ux, vy, wz = u3.times_(p3).xyz

995# u2, v2, w2 = u3.x2y2z2 # u3.times_(u3).xyz

996#

997# t = c2, c2, b2

998# m = fdot(t, u2, v2, w2) # a2 factored out

999# if m < EPS0: # zero or near-null LOS vector

1000# raise _Error(_near_(_null_))

1001#

1002# # a2 and b2 factored out, b2 == a2 and b2 / a2 == 1

1003# r = fsumf_(b2 * w2, c2 * v2, -v2 * z2, vy * wz * 2,

1004# c2 * u2, -u2 * z2, -w2 * x2, ux * wz * 2,

1005# -w2 * y2, -u2 * y2 * q2, -v2 * x2 * q2, ux * vy * 2 * q2)

1006# if r > 0:

1007# r = sqrt(r) * bc # == a * a * b * c / a2

1008# elif r < 0: # LOS pointing away from or missing the earth

1009# raise _Error(_opposite_ if max(ux, vy, wz) > 0 else _outside_)

1010#

1011# d = Fdot(t, ux, vy, wz).fadd_(r).fover(m) # -r for antipode, a2 factored out

1012# if d > 0: # POV inside or LOS missing, outside the earth

1013# s = fsumf_(_1_0, x2 / a2, y2 / b2, z2 / c2, _N_2_0) # like _sideOf

1014# raise _Error(_outside_ if s > 0 else _inside_)

1015# elif fsumf_(x2, y2, z2) < d**2: # d past earth center

1016# raise _Error(_too_(_distant_))

1017#

1018# r = p3.minus(u3.times(d))

1019# # h = p3.minus(r).length # distance to ellipsoid

1020

1021 r = _xnamed(r, name or hartzell.__name__)

1022 if LatLon_and_kwds:

1023 c = _MODS.cartesianBase.CartesianBase(r, datum=D, name=r.name)

1024 r = c.toLatLon(**LatLon_and_kwds)

1025 return r

1026

1027

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

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

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

1031 formula.

1032

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

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

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

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

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

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

1039 L{a_f2Tuple}) to use.

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

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

1042

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

1044

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

1046

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

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

1049 L{cosineLaw}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

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

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

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

1053

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

1055 '''

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

1057

1058

1059 def haversine_(phi2, phi1, lam21):

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

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

1062 formula.

1063

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

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

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

1067

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

1069

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

1071 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

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

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

1074

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

1076 '''

1077 def _hsin(rad):

1078 return sin(rad * _0_5)**2

1079

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

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

1082

1083

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

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

1086 traveling along a straight line at a given tilt.

1087

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

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

1090 B{C{radius}}).

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

1092

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

1094

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

1096

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

1098 (U{Shapiro et al. 2009, JTECH

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

1100 and U{Potvin et al. 2012, JTECH

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

1102 '''

1103 r = h = Radius(radius)

1104 d = fabs(Distance(distance))

1105 if d > h:

1106 d, h = h, d

1107

1108 if d > EPS0: # and h > EPS0

1109 d = d / h # /= h chokes PyChecker

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

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

1112 if s > 0:

1113 return h * sqrt(s) - r

1114

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

1116

1117

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

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

1120 above the (spherical) earth.

1121

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

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

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

1125

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

1127

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

1129

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

1131 '''

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

1133 if min(h, r) < 0:

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

1135

1136 if refraction:

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

1138 else:

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

1140 return sqrt0(d2)

1141

1142

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

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

1145 '''

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

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

1148 try:

1149 if wrap:

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

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

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

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

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

1155 d, m = None, _MODS.vector3d

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

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

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

1159 m = _MODS.sphericalNvector

1160 _i = m.intersection

1161 else:

1162 d = _spherical_datum(datum, name=n)

1163 if d.isSpherical:

1164 m = _MODS.sphericalTrigonometry

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

1166 elif d.isEllipsoidal:

1167 try:

1168 if d.ellipsoid.geodesic:

1169 pass

1170 m = _MODS.ellipsoidalKarney

1171 except ImportError:

1172 m = _MODS.ellipsoidalExact

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

1174 else:

1175 raise _TypeError(datum=datum)

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

1177

1178 except (TypeError, ValueError) as x:

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

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

1181

1182_idllmn6 = _idllmn6() # PYCHOK singleton

1183

1184

1185 def intersection2(lat1, lon1, bearing1,

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

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

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

1189

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

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

1192

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

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

1195 in C{meter} or ...

1196

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

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

1199

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

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

1202 is installed, otherwise ...

1203

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

1205

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

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

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

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

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

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

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

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

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

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

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

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

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

1219

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

1221 longitude of the intersection point.

1222

1223 @raise IntersectionError: Ambiguous or infinite intersection

1224 or colinear, parallel or otherwise

1225 non-intersecting lines.

1226

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

1228

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

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

1231

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

1233

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

1235 '''

1236 b1 = Bearing(bearing1=bearing1)

1237 b2 = Bearing(bearing2=bearing2)

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

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

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

1241 if d is None:

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

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

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

1245

1246 else:

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

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

1249 if isinstance(t, Intersection3Tuple): # ellipsoidal

1250 t, _, _ = t

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

1252 return t

1253

1254

1255 def intersections2(lat1, lon1, radius1,

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

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

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

1259

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

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

1262

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

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

1265 in C{meter} or ...

1266

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

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

1269 is installed, otherwise ...

1270

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

1272

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

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

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

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

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

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

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

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

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

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

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

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

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

1286

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

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

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

1290

1291 @raise IntersectionError: Concentric, antipodal, invalid or

1292 non-intersecting circles or no

1293 convergence.

1294

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

1296

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

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

1299 '''

1300 r1 = Radius_(radius1=radius1)

1301 r2 = Radius_(radius2=radius2)

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

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

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

1305 if d is None:

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

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

1308

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

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

1311

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

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

1314 Vector=_V2T)

1315 else:

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

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

1318

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

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

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

1322 return t

1323

1324

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

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

1327 opposite sides of the earth.

1328

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

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

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

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

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

1334

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

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

1337

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

1339 '''

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

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

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

1343

1344

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

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

1347 opposite sides of the earth.

1348

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

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

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

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

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

1354

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

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

1357

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

1359 '''

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

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

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

1363

1364

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

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

1367 '''

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

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

1370

1371

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

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

1374 '''

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

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

1377

1378

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

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

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

1382

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

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

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

1386

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

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

1389

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

1391 '''

1392 return (_90_0 - fabs(lat)) >= eps and (_180_0 - fabs(lon)) >= eps

1393

1394

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

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

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

1398

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

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

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

1402

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

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

1405

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

1407 '''

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

1409

1410

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

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

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

1414

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

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

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

1418

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

1420

1421 @see: Function L{philam2n_xyz}.

1422

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

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

1425 '''

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

1427

1428

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

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

1431 '''

1432 if fabs(b) > n:

1433 b = remainder(b, n2)

1434 if fabs(a) > n_2:

1435 r = remainder(a, n)

1436 if r != a:

1437 a = -r

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

1439 return float0_(a, b)

1440

1441

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

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

1444

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

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

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

1448

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

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

1451

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

1453 '''

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

1455 name=name or normal.__name__)

1456

1457

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

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

1460

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

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

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

1464

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

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

1467

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

1469 '''

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

1471 name=name or normal_.__name__)

1472

1473

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

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

1476 '''

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

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

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

1480

1481

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

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

1484

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

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

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

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

1489

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

1491

1492 @see: Function L{n_xyz2philam}.

1493 '''

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

1495

1496

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

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

1499

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

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

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

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

1504

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

1506

1507 @see: Function L{n_xyz2latlon}.

1508 '''

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

1510

1511

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

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

1514 '''

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

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

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

1518

1519

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

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

1522

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

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

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

1526

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

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

1529

1530 @see: Function L{opposing_}.

1531 '''

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

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

1534

1535

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

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

1538

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

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

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

1542

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

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

1545

1546 @see: Function L{opposing}.

1547 '''

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

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

1550

1551

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

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

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

1555

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

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

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

1559

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

1561

1562 @see: Function L{latlon2n_xyz}.

1563

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

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

1566 '''

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

1568

1569

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

1571 # (INTERNAL) See C{radical2} below

1572 # assert d > EPS0

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

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

1575

1576

1577 def radical2(distance, radius1, radius2):

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

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

1580 Circle-CircleIntersection.html>}.

1581

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

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

1584

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

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

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

1588

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

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

1591

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

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

1594

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

1596 B{C{radius2}}.

1597

1598 @see: U{Circle-Circle Intersection

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

1600 '''

1601 d = Distance_(distance, low=_0_0)

1602 r1 = Radius_(radius1=radius1)

1603 r2 = Radius_(radius2=radius2)

1604 if d > (r1 + r2):

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

1606 txt=_too_(_distant_))

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

1608 Radical2Tuple(_0_5, _0_0)

1609

1610

1611 class Radical2Tuple(_NamedTuple):

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

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

1614 '''

1615 _Names_ = (_ratio_, _xline_)

1616 _Units_ = ( Scalar, Scalar)

1617

1618

1619 def _radistance(inst):

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

1621 and L{hausdorff._HausdorffMeterRedians} classes.

1622 '''

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

1624 wrap_ = _xkwds_pop(kwds_, wrap=False)

1625 func_ = inst._func_

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

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

1628 wrap_ = _Wrap._philamop(wrap_)

1629 except TypeError:

1630 return inst.distance

1631

1632 def _philam(p):

1633 try:

1634 return p.phi, p.lam

1635 except AttributeError: # no .phi or .lam

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

1637

1638 def _func_wrap(point1, point2):

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

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

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

1642

1643 inst._units = inst._units_

1644 return _func_wrap

1645

1646

1647 def _scale_deg(lat1, lat2): # degrees

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

1649 m = fabs(lat1 + lat2) * _0_5

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

1651

1652

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

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

1655 m = fabs(phi1 + phi2) * _0_5

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

1657

1658

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

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

1661 '''

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

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

1664

1665

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

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

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

1669 formula.

1670

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

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

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

1674 @arg lon2: End longitude (C{degrees}).

1675 @kwarg datum: Datum (L{Datum}) or ellipsoid (L{Ellipsoid},

1676 L{Ellipsoid2} or L{a_f2Tuple}) to use.

1677 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll

1678 B{C{lat2}} and B{C{lon2}} (C{bool}).

1679

1680 @return: Distance (C{meter}, same units as the B{C{datum}}'s

1681 ellipsoid axes).

1682

1683 @raise TypeError: Invalid B{C{datum}}.

1684

1685 @see: Functions L{thomas_}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

1686 L{cosineLaw}, L{equirectangular}, L{euclidean}, L{flatLocal}/L{hubeny},

1687 L{flatPolar}, L{haversine}, L{vincentys} and method L{Ellipsoid.distance2}.

1688 '''

1689 return _dE(thomas_, datum, wrap, lat1, lon1, lat2, lon2)

1690

1691

1692 def thomas_(phi2, phi1, lam21, datum=_WGS84):

1693 '''Compute the I{angular} distance between two (ellipsoidal) points using

1694 U{Thomas'<https://apps.DTIC.mil/dtic/tr/fulltext/u2/703541.pdf>}

1695 formula.

1696

1697 @arg phi2: End latitude (C{radians}).

1698 @arg phi1: Start latitude (C{radians}).

1699 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).

1700 @kwarg datum: Datum or ellipsoid to use (L{Datum}, L{Ellipsoid},

1701 L{Ellipsoid2} or L{a_f2Tuple}).

1702

1703 @return: Angular distance (C{radians}).

1704

1705 @raise TypeError: Invalid B{C{datum}}.

1706

1707 @see: Functions L{thomas}, L{cosineAndoyerLambert_},

1708 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

1709 L{equirectangular_}, L{euclidean_}, L{flatLocal_}/L{hubeny_},

1710 L{flatPolar_}, L{haversine_} and L{vincentys_} and U{Geodesy-PHP

1711 <https://GitHub.com/jtejido/geodesy-php/blob/master/src/Geodesy/

1712 Distance/ThomasFormula.php>}.

1713 '''

1714 s2, c2, s1, c1, r, _ = _sincosa6(phi2, phi1, lam21)

1715 if r and isnon0(c1) and isnon0(c2):

1716 E = _ellipsoidal(datum, thomas_)

1717 if E.f:

1718 r1 = atan2(E.b_a * s1, c1)

1719 r2 = atan2(E.b_a * s2, c2)

1720

1721 j = (r2 + r1) * _0_5

1722 k = (r2 - r1) * _0_5

1723 sj, cj, sk, ck, h, _ = sincos2_(j, k, lam21 * _0_5)

1724

1725 h = fsumf_(sk**2, (ck * h)**2, -(sj * h)**2)

1726 u = _1_0 - h

1727 if isnon0(u) and isnon0(h):

1728 r = atan(sqrt0(h / u)) * 2 # == acos(1 - 2 * h)

1729 sr, cr = sincos2(r)

1730 if isnon0(sr):

1731 u = 2 * (sj * ck)**2 / u

1732 h = 2 * (sk * cj)**2 / h

1733 x = u + h

1734 y = u - h

1735

1736 s = r / sr

1737 e = 4 * s**2

1738 d = 2 * cr

1739 a = e * d

1740 b = 2 * r

1741 c = s - (a - d) * _0_5

1742 f = E.f * _0_25

1743

1744 t = fsumf_(a * x, -b * y, c * x**2, -d * y**2, e * x * y)

1745 r -= fsumf_(s * x, -y, -t * f * _0_25) * f * sr

1746 return r

1747

1748

1749 def vincentys(lat1, lon1, lat2, lon2, radius=R_M, wrap=False):

1750 '''Compute the distance between two (spherical) points using

1751 U{Vincenty's<https://WikiPedia.org/wiki/Great-circle_distance>}

1752 spherical formula.

1753

1754 @arg lat1: Start latitude (C{degrees}).

1755 @arg lon1: Start longitude (C{degrees}).

1756 @arg lat2: End latitude (C{degrees}).

1757 @arg lon2: End longitude (C{degrees}).

1758 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum})

1759 or ellipsoid (L{Ellipsoid}, L{Ellipsoid2} or

1760 L{a_f2Tuple}) to use.

1761 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll

1762 B{C{lat2}} and B{C{lon2}} (C{bool}).

1763

1764 @return: Distance (C{meter}, same units as B{C{radius}}).

1765

1766 @raise UnitError: Invalid B{C{radius}}.

1767

1768 @see: Functions L{vincentys_}, L{cosineAndoyerLambert},

1769 L{cosineForsytheAndoyerLambert},L{cosineLaw}, L{equirectangular},

1770 L{euclidean}, L{flatLocal}/L{hubeny}, L{flatPolar},

1771 L{haversine} and L{thomas} and methods L{Ellipsoid.distance2},

1772 C{LatLon.distanceTo*} and C{LatLon.equirectangularTo}.

1773

1774 @note: See note at function L{vincentys_}.

1775 '''

1776 return _dS(vincentys_, radius, wrap, lat1, lon1, lat2, lon2)

1777

1778

1779 def vincentys_(phi2, phi1, lam21):

1780 '''Compute the I{angular} distance between two (spherical) points using

1781 U{Vincenty's<https://WikiPedia.org/wiki/Great-circle_distance>}

1782 spherical formula.

1783

1784 @arg phi2: End latitude (C{radians}).

1785 @arg phi1: Start latitude (C{radians}).

1786 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).

1787

1788 @return: Angular distance (C{radians}).

1789

1790 @see: Functions L{vincentys}, L{cosineAndoyerLambert_},

1791 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

1792 L{equirectangular_}, L{euclidean_}, L{flatLocal_}/L{hubeny_},

1793 L{flatPolar_}, L{haversine_} and L{thomas_}.

1794

1795 @note: Functions L{vincentys_}, L{haversine_} and L{cosineLaw_}

1796 produce equivalent results, but L{vincentys_} is suitable

1797 for antipodal points and slightly more expensive (M{3 cos,

1798 3 sin, 1 hypot, 1 atan2, 6 mul, 2 add}) than L{haversine_}

1799 (M{2 cos, 2 sin, 2 sqrt, 1 atan2, 5 mul, 1 add}) and

1800 L{cosineLaw_} (M{3 cos, 3 sin, 1 acos, 3 mul, 1 add}).

1801 '''

1802 s1, c1, s2, c2, s21, c21 = sincos2_(phi1, phi2, lam21)

1803

1804 c = c2 * c21

1805 x = s1 * s2 + c1 * c

1806 y = c1 * s2 - s1 * c

1807 return atan2(hypot(c2 * s21, y), x)

1808

1809# **) MIT License

1810#

1811# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved.

1812#

1813# Permission is hereby granted, free of charge, to any person obtaining a

1814# copy of this software and associated documentation files (the "Software"),

1815# to deal in the Software without restriction, including without limitation

1816# the rights to use, copy, modify, merge, publish, distribute, sublicense,

1817# and/or sell copies of the Software, and to permit persons to whom the

1818# Software is furnished to do so, subject to the following conditions:

1819#

1820# The above copyright notice and this permission notice shall be included

1821# in all copies or substantial portions of the Software.

1822#

1823# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS

1824# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

1825# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL

1826# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR

1827# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,

1828# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR

1829# OTHER DEALINGS IN THE SOFTWARE.