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 _hartzell2 # _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.16'

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 t = p1.philam + p2.philam

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

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

158 name=_bearingTo2.__name__)

159

160

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

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

163 lat2 - lat1)} between two points.

164

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

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

167

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

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

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

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

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

173 mean latitude (C{bool}).

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

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

176

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

178

179 @note: Courtesy of Martin Schultz.

180

181 @see: U{Local, flat earth approximation

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

183 '''

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

185 if adjust: # scale delta lon

186 d_lon *= _scale_deg(lat1, lat2)

187 return atan2b(d_lon, lat2 - lat1)

188

189

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

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

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

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

194

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

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

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

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

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

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

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

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

203

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

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

206

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

208

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

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

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

212 L{Ellipsoid.distance2}.

213 '''

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

215

216

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

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

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

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

221

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

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

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

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

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

227

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

229

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

231

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

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

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

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

236 AndoyerLambert.php>}.

237 '''

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

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

240 E = _ellipsoidal(datum, cosineAndoyerLambert_)

241 if E.f: # ellipsoidal

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

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

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

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

246 if r:

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

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

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

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

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

252 return r

253

254

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

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

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

258 <https://www.Movable-Type.co.UK/scripts/latlong.html#cosine-law>} 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<https://www2.UNB.Ca/gge/Pubs/TR77.pdf>} correction 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 t = fsumf_( a * x, e * y**2, b * y, -c * x**2, d * x * y)

322

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 Cosines

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

330

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

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

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

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

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

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

337 L{a_f2Tuple}) to use.

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

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

340

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

342 ellipsoid or datum axes).

343

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

345

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

347 L{cosineForsytheAndoyerLambert}, L{equirectangular}, L{euclidean},

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

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

350

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

352 '''

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

354

355

356 def cosineLaw_(phi2, phi1, lam21):

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

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

359

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

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

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

363

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

365

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

367 L{cosineForsytheAndoyerLambert_}, L{equirectangular_},

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

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

370

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

372 '''

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

374

375

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

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

378 '''

379 if wrap:

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

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

382 else: # for backward compaibility

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

384

385

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

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

388 '''

389 E = _ellipsoidal(earth, func_)

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

391 return r * E.a

392

393

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

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

396 '''

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

398 if radius is not R_M:

399 _, lat1, _, lat2, _ = wrap_lls

400 radius = _mean_radius(radius, lat1, lat2)

401 return r * radius

402

403

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

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

406 '''

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

408 if radius:

409 _, lat1, _, lat2, _ = wrap_lls

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

411 return r

412

413

414 def _ellipsoidal(earth, where):

415 '''(INTERNAL) Helper for distances.

416 '''

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

418 earth if isinstance(earth, Ellipsoid) else

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

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

421

422

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

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

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

426

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

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

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

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

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

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

433 L{a_f2Tuple}).

434 @kwarg adjust_limit_wrap: Optional keyword arguments for

435 function L{equirectangular_}.

436

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

438 the ellipsoid or datum axes).

439

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

441

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

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

444 approximate or accurate distance functions.

445 '''

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

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

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

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

450

451

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

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

454 and L{hausdorff._HausdorffMeterRedians} classes.

455 '''

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

457

458

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

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

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

462

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

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

465

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

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

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

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

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

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

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

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

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

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

476

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

478 unroll_lon2)} in C{degrees squared}.

479

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

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

482 set to C{True}.

483

484 @see: U{Local, flat earth approximation

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

486 L{equirectangular}, L{cosineAndoyerLambert},

487 L{cosineForsytheAndoyerLambert}, L{cosineLaw}, L{euclidean},

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

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

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

491 '''

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

493 d_lat = lat2 - lat1

494

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

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

497 if d > limit:

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

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

500 limit=limit, wrap=wrap)

501 raise LimitError(s, txt=t)

502

503 if adjust: # scale delta lon

504 d_lon *= _scale_deg(lat1, lat2)

505

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

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

508

509

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

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

512

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

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

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

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

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

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

519 L{a_f2Tuple}) to use.

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

521 the mean latitude (C{bool}).

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

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

524

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

526 ellipsoid or datum axes).

527

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

529

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

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

532 L{euclidean_}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

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

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

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

536 '''

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

538

539

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

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

542

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

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

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

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

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

548

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

550

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

552 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_}, L{equirectangular_},

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

554 and L{vincentys_}.

555 '''

556 if adjust:

557 lam21 *= _scale_rad(phi2, phi1)

558 return euclid(phi2 - phi1, lam21)

559

560

561 def excessAbc_(A, b, c):

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

563 and the included (small) angle.

564

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

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

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

568

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

570

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

572

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

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

575 '''

576 A = Radians_(A=A)

577 b = Radians_(b=b) * _0_5

578 c = Radians_(c=c) * _0_5

579

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

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

582

583

584 def excessCagnoli_(a, b, c):

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

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

587

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

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

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

591

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

593

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

595

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

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

598 '''

599 a = Radians_(a=a)

600 b = Radians_(b=b)

601 c = Radians_(c=c)

602

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

604 _s = sin

605 r = _s(s) * _s(s - a) * _s(s - b) * _s(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>}'s 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 _t = tan_2

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

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

654 return Radians(LHuilier=r * _4_0)

655

656

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

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

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

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

661 method.

662

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

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

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

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

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

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

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

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

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

672

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

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

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

676

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

678

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

680

681 @raise ValueError: Semi-circular longitudinal delta.

682

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

684 '''

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

686

687

688 def excessKarney_(phi2, phi1, lam21):

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

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

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

692 method.

693

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

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

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

697

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

699

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

701

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

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

704 '''

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

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

707 #

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

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

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

711 #

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

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

714 _t = tan_2

715 t2 = _t(phi2)

716 t1 = _t(phi1)

717 t = _t(lam21, lam21=None)

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

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

720

721

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

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

724#

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

726#

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

728#

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

730#

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

732#

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

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

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

736#

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

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

739#

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

741#

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

743# inverse Gudermannian) function

744#

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

746#

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

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

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

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

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

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

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

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

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

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

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

758# - Charles Karney

759

760

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

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

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

764

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

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

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

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

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

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

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

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

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

774

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

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

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

778

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

780

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

782

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

784 '''

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

786

787

788 def excessQuad_(phi2, phi1, lam21):

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

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

791

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

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

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

795

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

797

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

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

800 '''

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

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

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

804

805

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

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

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

809 wiki/Geographical_distance#Ellipsoidal_Earth_projected_to_a_plane>}

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

811

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

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

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

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

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

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

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

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

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

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

822

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

824 ellipsoid axes).

825

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

827

828 @note: The meridional and prime_vertical radii of curvature

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

830

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

832 L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

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

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

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

836 '''

837 E = _ellipsoidal(datum, flatLocal)

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

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

840

841 hubeny = flatLocal # PYCHOK for Karl Hubeny

842

843

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

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

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

847 wiki/Geographical_distance#Ellipsoidal_Earth_projected_to_a_plane>}

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

849

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

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

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

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

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

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

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

857

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

859

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

861

862 @note: The meridional and prime_vertical radii of curvature

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

864

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

866 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_}, L{flatPolar_},

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

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

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

870 '''

871 E = _ellipsoidal(datum, flatLocal_)

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

873

874 hubeny_ = flatLocal_ # PYCHOK for Karl Hubeny

875

876

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

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

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

880 Geographical_distance#Polar_coordinate_flat-Earth_formula>}

881 formula.

882

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

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

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

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

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

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

889 L{a_f2Tuple}) to use.

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

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

892

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

894 ellipsoid or datum axes).

895

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

897

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

899 L{cosineForsytheAndoyerLambert},L{cosineLaw},

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

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

902 L{vincentys}.

903 '''

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

905

906

907 def flatPolar_(phi2, phi1, lam21):

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

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

910 Geographical_distance#Polar_coordinate_flat-Earth_formula>}

911 formula.

912

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

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

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

916

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

918

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

920 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

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

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

923 '''

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

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

926 if a < b:

927 a, b = b, a

928 if a < EPS0:

929 a = _0_0

930 elif b > 0:

931 b = b / a # /= chokes PyChecker

932 c = b * cos(lam21) * _2_0

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

934 a *= sqrt0(c)

935 return a

936

937

938 def _hartzell(inst, los, earth, **kwds):

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

940 '''

941 if earth is not None:

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

943 inst = inst.toDatum(earth)

944 h = inst.height

945 if h > 0: # EPS0

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

947 elif h < 0: # EPS0

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

949 else:

950 r = inst

951 return r

952

953

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

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

956 from a Point-Of-View in space.

957

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

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

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

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

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

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

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

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

966 point plus C{LatLon} keyword arguments, include

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

968

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

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

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

972

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

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

975 the earth or points in an opposite direction.

976

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

978

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

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

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

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

983 '''

984 n = hartzell.__name__

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

986 _spherical_datum(earth, name=n)

987 try:

988 r, h = _MODS.triaxials._hartzell2(pov, los, D.ellipsoid._triaxial)

989 except Exception as x:

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

991

992 r = _xnamed(r, name or n)

993 C = _MODS.cartesianBase.CartesianBase

994 if LatLon_and_kwds:

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

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

997 elif isinstance(r, C):

998 r.height = h

999 return r

1000

1001

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

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

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

1005 formula.

1006

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

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

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

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

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

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

1013 L{a_f2Tuple}) to use.

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

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

1016

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

1018

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

1020

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

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

1023 L{cosineLaw}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

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

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

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

1027

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

1029 '''

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

1031

1032

1033 def haversine_(phi2, phi1, lam21):

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

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

1036 formula.

1037

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

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

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

1041

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

1043

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

1045 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

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

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

1048

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

1050 '''

1051 def _hsin(rad):

1052 return sin(rad * _0_5)**2

1053

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

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

1056

1057

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

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

1060 traveling along a straight line at a given tilt.

1061

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

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

1064 B{C{radius}}).

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

1066

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

1068

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

1070

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

1072 (U{Shapiro et al. 2009, JTECH

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

1074 and U{Potvin et al. 2012, JTECH

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

1076 '''

1077 r = h = Radius(radius)

1078 d = fabs(Distance(distance))

1079 if d > h:

1080 d, h = h, d

1081

1082 if d > EPS0: # and h > EPS0

1083 d = d / h # /= h chokes PyChecker

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

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

1086 if s > 0:

1087 return h * sqrt(s) - r

1088

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

1090

1091

1092 def heightOrthometric(h_ll, N):

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

1094

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

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

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

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

1099

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

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

1102

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

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

1105 6 and module L{pygeodesy.geoids}.

1106 '''

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

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

1109

1110

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

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

1113 above the (spherical) earth.

1114

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

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

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

1118

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

1120

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

1122

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

1124 '''

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

1126 if min(h, r) < 0:

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

1128

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

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

1131 return sqrt0(d2)

1132

1133

1134 class _idllmn6(object): # see also .geodesicw._wargs, .latlonBase._toCartesian3, .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.