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 W_args_kwds_count2

10# from pygeodesy.cartesianBase import CartesianBase # _MODS

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

12 _0_0s, float0_, isnon0, remainder, _umod_PI2, \

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

14 _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 _xcallable,_xkwds, _xkwds_pop2

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

22 from pygeodesy.fsums import fsumf_, Fmt, unstr

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

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

25 from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS

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

27 _dunder_nameof

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

29 Intersection3Tuple, PhiLam2Tuple, Vector3Tuple

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

31# from pygeodesy.triaxials import _hartzell3 # _MODS

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

33 Distance_, Height, Lamd, Lat, Lon, Meter_, Phid, \

34 Radians, Radians_, Radius, Radius_, Scalar, _100km

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

36 tan_2, sincos2, sincos2_, sincos2d_, _Wrap

37# from pygeodesy.vector3d import _otherV3d # _MODS

38# from pygeodesy.vector3dBase import _xyz_y_z3 # _MODS

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

40# sphericalNvector, sphericalTrigonometry # _MODS

41

42 from contextlib import contextmanager

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

44

45__all__ = _ALL_LAZY.formy

46__version__ = '24.09.27'

47

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

49_ratio_ = 'ratio'

50_xline_ = 'xline'

51

52

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

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

55 '''

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

57 if r == a:

58 r = -r

59 b += n

60 if fabs(b) > n:

61 b = remainder(b, n2)

62 return float0_(r, b)

63

64

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

66 '''Return the antipode, the point diametrically opposite to a given

67 point in C{degrees}.

68

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

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

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

72

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

74

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

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

77 '''

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

79

80

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

82 '''Return the antipode, the point diametrically opposite to a given

83 point in C{radians}.

84

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

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

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

88

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

90

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

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

93 '''

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

95

96

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

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

99 between two (spherical) points.

100

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

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

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

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

105 @kwarg final_wrap: Optional keyword arguments for function

106 L{pygeodesy.bearing_}.

107

108 @return: Initial or final bearing (compass C{degrees360}) or zero if

109 both points coincide.

110 '''

111 r = bearing_(Phid(lat1=lat1), Lamd(lon1=lon1),

112 Phid(lat2=lat2), Lamd(lon2=lon2), **final_wrap)

113 return degrees(r)

114

115

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

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

118 two (spherical) points.

119

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

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

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

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

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

125 (C{bool}).

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

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

128

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

130 are coincident.

131

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

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

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

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

136 '''

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

138 if final: # swap plus PI

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

140 r = PI3

141 else:

142 r = PI2

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

144

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

146 y = sdb * ca2

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

148

149

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

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

152 '''

153 try: # for LatLon_ and ellipsoidal LatLon

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

155 except AttributeError:

156 pass

157 # XXX spherical version, OK for ellipsoidal ispolar?

158 t = p1.philam + p2.philam

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

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

161 name__=_bearingTo2)

162

163

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

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

166 lat2 - lat1)} between two points.

167

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

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

170

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

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

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

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

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

176 mean latitude (C{bool}).

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

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

179

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

181

182 @note: Courtesy of Martin Schultz.

183

184 @see: U{Local, flat earth approximation

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

186 '''

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

188 if adjust: # scale delta lon

189 d_lon *= _scale_deg(lat1, lat2)

190 return atan2b(d_lon, lat2 - lat1)

191

192

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

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

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

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

197

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

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

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

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

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

203 L{a_f2Tuple}) to use.

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

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

206

207 @return: Distance (C{meter}, same units as the B{C{datum}}'s ellipsoid axes or

208 C{radians} if C{B{datum} is None}).

209

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

211

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

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

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

215 L{Ellipsoid.distance2}.

216 '''

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

218

219

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

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

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

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

224

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

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

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

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

229 L{a_f2Tuple}) to use.

230

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

232

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

234

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

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

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

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

239 AndoyerLambert.php>}.

240 '''

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

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

243 E = _ellipsoidal(datum, cosineAndoyerLambert_)

244 if E.f: # ellipsoidal

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

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

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

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

249 if r:

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

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

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

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

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

255 return r

256

257

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

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

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

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

262

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

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

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

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

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

268 L{a_f2Tuple}) to use.

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

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

271

272 @return: Distance (C{meter}, same units as the B{C{datum}}'s ellipsoid axes or

273 C{radians} if C{B{datum} is None}).

274

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

276

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

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

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

280 L{Ellipsoid.distance2}.

281 '''

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

283

284

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

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

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

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

289 formula.

290

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

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

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

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

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

296

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

298

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

300

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

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

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

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

305 Distance/ForsytheCorrection.php>}.

306 '''

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

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

309 E = _ellipsoidal(datum, cosineForsytheAndoyerLambert_)

310 if E.f: # ellipsoidal

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

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

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

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

315 x = s + t

316 y = s - t

317

318 s = 8 * r**2 / sr

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

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

321 b = -2 * d

322 e = 30 * s2r

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

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

325

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

327 return r

328

329

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

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

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

333

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

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

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

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

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

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

340 L{a_f2Tuple}) to use.

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

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

343

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

345 ellipsoid or datum axes).

346

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

348

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

350 L{cosineForsytheAndoyerLambert}, L{equirectangular}, L{euclidean},

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

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

353

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

355 '''

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

357

358

359 def cosineLaw_(phi2, phi1, lam21):

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

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

362

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

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

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

366

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

368

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

370 L{cosineForsytheAndoyerLambert_}, L{euclidean_},

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

372 L{thomas_} and L{vincentys_}.

373

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

375 '''

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

377

378

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

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

381 '''

382 if wrap:

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

384 return radians(lat2), Phid(lat1=lat1), radians(d_lon)

385 else: # for backward compaibility

386 return Phid(lat2=lat2), Phid(lat1=lat1), Phid(d_lon=lon2 - lon1)

387

388

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

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

391 '''

392 E = _ellipsoidal(earth, func_)

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

394 return r * E.a

395

396

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

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

399 '''

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

401 if radius is not R_M:

402 _, lat1, _, lat2, _ = wrap_lls

403 radius = _mean_radius(radius, lat1, lat2)

404 return r * radius

405

406

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

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

409 '''

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

411 if radius:

412 _, lat1, _, lat2, _ = wrap_lls

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

414 return r

415

416

417 def _ellipsoidal(earth, where):

418 '''(INTERNAL) Helper for distances.

419 '''

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

421 earth if isinstance(earth, Ellipsoid) else

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

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

424

425

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

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

428 / Projection<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}) or ellipsoid

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

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

437

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

439

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

441

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

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

444 '''

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

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

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

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

449

450

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

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

453 and L{hausdorff._HausdorffMeterRedians} classes.

454 '''

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

456

457

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

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

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

461

462 This approximation is valid for short distance of several hundred Km or Miles, see

463 the B{C{limit}} keyword argument and L{LimitError}.

464

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

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

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

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

469 @kwarg adjust: Adjust the wrapped, unrolled longitudinal delta by the cosine of the mean

470 latitude (C{bool}).

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

472 or C{0} for unlimited.

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

474 (C{bool}).

475

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

477 in C{degrees squared}.

478

479 @raise LimitError: If the lat- and/or longitudinal delta exceeds the B{C{-limit..limit}}

480 range and L{limiterrors<pygeodesy.limiterrors>} is C{True}.

481

482 @see: U{Local, flat earth approximation<https://www.EdWilliams.org/avform.htm#flat>},

483 functions L{equirectangular}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

484 L{cosineLaw}, L{euclidean}, L{flatLocal}/L{hubeny}, L{flatPolar}, L{haversine},

485 L{thomas} and L{vincentys} and methods L{Ellipsoid.distance2}, C{LatLon.distanceTo*}

486 and C{LatLon.equirectangularTo}.

487 '''

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

489 d_lat = lat2 - lat1

490

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

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

493 if d > limit:

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

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

496 limit=limit, wrap=wrap)

497 raise LimitError(s, txt=t)

498

499 if adjust: # scale delta lon

500 d_lon *= _scale_deg(lat1, lat2)

501

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

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

504

505

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

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

508

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

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

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

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

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

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

515 L{a_f2Tuple}) to use.

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

517 the mean latitude (C{bool}).

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

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

520

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

522 ellipsoid or datum axes).

523

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

525

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

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

528 L{euclidean_}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

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

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

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

532 '''

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

534

535

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

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

538

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

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

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

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

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

544

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

546

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

548 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

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

550 L{thomas_} and L{vincentys_}.

551 '''

552 if adjust:

553 lam21 *= _scale_rad(phi2, phi1)

554 return euclid(phi2 - phi1, lam21)

555

556

557 def excessAbc_(A, b, c):

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

559 and the included (small) angle.

560

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

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

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

564

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

566

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

568

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

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

571 '''

572 A = Radians_(A=A)

573 b = Radians_(b=b) * _0_5

574 c = Radians_(c=c) * _0_5

575

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

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

578

579

580 def excessCagnoli_(a, b, c):

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

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

583

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

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

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

587

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

589

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

591

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

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

594 '''

595 a = Radians_(a=a)

596 b = Radians_(b=b)

597 c = Radians_(c=c)

598

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

600 _s = sin

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

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

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

604 return Radians(Cagnoli=r * _2_0)

605

606

607 def excessGirard_(A, B, C):

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

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

610

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

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

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

614

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

616

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

618

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

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

621 '''

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

623 Radians_(B=B),

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

625

626

627 def excessLHuilier_(a, b, c):

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

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

630

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

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

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

634

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

636

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

638

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

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

641 '''

642 a = Radians_(a=a)

643 b = Radians_(b=b)

644 c = Radians_(c=c)

645

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

647 _t = tan_2

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

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

650 return Radians(LHuilier=r * _4_0)

651

652

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

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

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

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

657 method.

658

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

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

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

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

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

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

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

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

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

668

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

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

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

672

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

674

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

676

677 @raise ValueError: Semi-circular longitudinal delta.

678

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

680 '''

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

682

683

684 def excessKarney_(phi2, phi1, lam21):

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

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

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

688 method.

689

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

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

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

693

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

695

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

697

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

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

700 '''

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

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

703 #

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

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

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

707 #

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

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

710 _t = tan_2

711 t2 = _t(phi2)

712 t1 = _t(phi1)

713 t = _t(lam21, lam21=None)

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

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

716

717

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

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

720#

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

722#

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

724#

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

726#

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

728#

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

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

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

732#

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

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

735#

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

737#

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

739# inverse Gudermannian) function

740#

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

742#

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

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

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

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

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

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

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

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

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

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

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

754# - Charles Karney

755

756

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

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

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

760

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

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

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

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

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

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

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

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

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

770

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

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

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

774

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

776

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

778

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

780 '''

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

782

783

784 def excessQuad_(phi2, phi1, lam21):

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

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

787

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

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

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

791

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

793

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

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

796 '''

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

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

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

800

801

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

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

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

805 wiki/Geographical_distance#Ellipsoidal_Earth_projected_to_a_plane>}

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

807

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

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

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

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

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

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

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

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

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

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

818

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

820 ellipsoid axes).

821

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

823

824 @note: The meridional and prime_vertical radii of curvature

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

826

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

828 L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

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

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

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

832 '''

833 E = _ellipsoidal(datum, flatLocal)

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

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

836

837 hubeny = flatLocal # PYCHOK for Karl Hubeny

838

839

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

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

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

843 wiki/Geographical_distance#Ellipsoidal_Earth_projected_to_a_plane>}

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

845

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

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

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

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

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

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

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

853

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

855

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

857

858 @note: The meridional and prime_vertical radii of curvature

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

860

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

862 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_}, L{flatPolar_},

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

864 U{local, flat earth approximation

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

866 '''

867 E = _ellipsoidal(datum, flatLocal_)

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

869

870 hubeny_ = flatLocal_ # PYCHOK for Karl Hubeny

871

872

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

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

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

876 Geographical_distance#Polar_coordinate_flat-Earth_formula>}

877 formula.

878

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

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

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

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

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

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

885 L{a_f2Tuple}) to use.

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

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

888

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

890 ellipsoid or datum axes).

891

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

893

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

895 L{cosineForsytheAndoyerLambert},L{cosineLaw},

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

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

898 L{vincentys}.

899 '''

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

901

902

903 def flatPolar_(phi2, phi1, lam21):

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

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

906 Geographical_distance#Polar_coordinate_flat-Earth_formula>}

907 formula.

908

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

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

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

912

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

914

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

916 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

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

918 L{thomas_} and L{vincentys_}.

919 '''

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

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

922 if a < b:

923 a, b = b, a

924 if a < EPS0:

925 a = _0_0

926 elif b > 0:

927 b = b / a # /= chokes PyChecker

928 c = b * cos(lam21) * _2_0

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

930 a *= sqrt0(c)

931 return a

932

933

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

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

936 '''

937 if earth is None:

938 earth = pov.datum

939 else:

940 earth = _spherical_datum(earth, name__=hartzell)

941 pov = pov.toDatum(earth)

942 h = pov.height

943 if h < 0: # EPS0

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

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

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

947

948

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

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

951 a Point-Of-View in space.

952

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

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

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

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

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

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

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

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

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

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

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

964

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

966 given B{C{LatLon}} instance) with attribute C{height} set to the

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

968

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

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

971 away from the earth.

972

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

974

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

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

977 '''

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

979 try:

980 D = _spherical_datum(earth, name__=hartzell)

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

982

983 C = _MODS.cartesianBase.CartesianBase

984 if LatLon_and_kwds:

985 c = C(r, datum=D)

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

987 elif isinstance(r, C):

988 r.height = h

989 if i:

990 r._iteration = i

991 except Exception as x:

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

993 **LatLon_and_kwds)

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

995

996

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

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

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

1000 formula.

1001

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

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

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

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

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

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

1008 L{a_f2Tuple}) to use.

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

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

1011

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

1013

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

1015

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

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

1018 L{cosineLaw}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

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

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

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

1022

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

1024 '''

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

1026

1027

1028 def haversine_(phi2, phi1, lam21):

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

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

1031 formula.

1032

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

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

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

1036

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

1038

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

1040 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

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

1042 L{thomas_} and L{vincentys_}.

1043

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

1045 '''

1046 def _hsin(rad):

1047 return sin(rad * _0_5)**2

1048

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

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

1051

1052

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

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

1055 traveling along a straight line at a given tilt.

1056

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

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

1059 B{C{radius}}).

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

1061

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

1063

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

1065

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

1067 (U{Shapiro et al. 2009, JTECH

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

1069 and U{Potvin et al. 2012, JTECH

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

1071 '''

1072 r = h = Radius(radius)

1073 d = fabs(Distance(distance))

1074 if d > h:

1075 d, h = h, d

1076

1077 if d > EPS0: # and h > EPS0

1078 d = d / h # /= h chokes PyChecker

1079 s = sin(Phid(angle=angle, clip=_180_0))

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

1081 if s > 0:

1082 return h * sqrt(s) - r

1083

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

1085

1086

1087 def heightOrthometric(h_ll, N):

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

1089

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

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

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

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

1094

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

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

1097

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

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

1100 6 and module L{pygeodesy.geoids}.

1101 '''

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

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

1104

1105

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

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

1108 (spherical) earth.

1109

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

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

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

1113

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

1115

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

1117

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

1119 '''

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

1121 if min(h, r) < 0:

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

1123

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

1125 fsumf_(r, r, h)) * h

1126 return sqrt0(d2)

1127

1128

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

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

1131 '''

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

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

1134 try:

1135 if wrap:

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

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

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

1139 n = _dunder_nameof(intersections2 if s else intersection2)

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

1141 d, m = None, _MODS.vector3d

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

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

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

1145 m = _MODS.sphericalNvector

1146 _i = m.intersection

1147 else:

1148 d = _spherical_datum(datum, name=n)

1149 if d.isSpherical:

1150 m = _MODS.sphericalTrigonometry

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

1152 elif d.isEllipsoidal:

1153 try:

1154 if d.ellipsoid.geodesic:

1155 pass

1156 m = _MODS.ellipsoidalKarney

1157 except ImportError:

1158 m = _MODS.ellipsoidalExact

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

1160 else:

1161 raise _TypeError(datum=datum)

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

1163

1164 except (TypeError, ValueError) as x:

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

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

1167

1168_idllmn6 = _idllmn6() # PYCHOK singleton

1169

1170

1171 def intersection2(lat1, lon1, bearing1,

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

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

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

1175

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

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

1178

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

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

1181 in C{meter} or ...

1182

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

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

1185

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

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

1188 is installed, otherwise ...

1189

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

1191

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

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

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

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

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

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

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

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

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

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

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

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

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

1205

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

1207 longitude of the intersection point.

1208

1209 @raise IntersectionError: Ambiguous or infinite intersection

1210 or colinear, parallel or otherwise

1211 non-intersecting lines.

1212

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

1214

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

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

1217

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

1219

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

1221 '''

1222 b1 = Bearing(bearing1=bearing1)

1223 b2 = Bearing(bearing2=bearing2)

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

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

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

1227 if d is None:

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

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

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

1231

1232 else:

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

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

1235 if isinstance(t, Intersection3Tuple): # ellipsoidal

1236 t, _, _ = t

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

1238 return t

1239

1240

1241 def intersections2(lat1, lon1, radius1,

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

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

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

1245

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

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

1248

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

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

1251 in C{meter} or ...

1252

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

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

1255 is installed, otherwise ...

1256

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

1258

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

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

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

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

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

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

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

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

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

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

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

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

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

1272

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

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

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

1276

1277 @raise IntersectionError: Concentric, antipodal, invalid or

1278 non-intersecting circles or no

1279 convergence.

1280

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

1282

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

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

1285 '''

1286 r1 = Radius_(radius1=radius1)

1287 r2 = Radius_(radius2=radius2)

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

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

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

1291 if d is None:

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

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

1294

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

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

1297

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

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

1300 Vector=_V2T)

1301 else:

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

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

1304

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

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

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

1308 return t

1309

1310

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

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

1313 opposite sides of the earth.

1314

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

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

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

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

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

1320

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

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

1323

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

1325 '''

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

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

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

1329

1330

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

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

1333 opposite sides of the earth.

1334

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

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

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

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

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

1340

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

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

1343

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

1345 '''

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

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

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

1349

1350

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

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

1353 '''

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

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

1356

1357

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

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

1360 '''

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

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

1363

1364

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

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

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

1368

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

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

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

1372

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

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

1375

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

1377 '''

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

1379

1380

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

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

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

1384

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

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

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

1388

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

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

1391

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

1393 '''

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

1395

1396

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

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

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

1400

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

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

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

1404

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

1406

1407 @see: Function L{philam2n_xyz}.

1408

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

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

1411 '''

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

1413

1414

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

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

1417 '''

1418 if fabs(b) > n:

1419 b = remainder(b, n2)

1420 if fabs(a) > n_2:

1421 r = remainder(a, n)

1422 if r != a:

1423 a = -r

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

1425 return float0_(a, b)

1426

1427

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

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

1430

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

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

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

1434

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

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

1437

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

1439 '''

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

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

1442

1443

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

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

1446

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

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

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

1450

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

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

1453

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

1455 '''

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

1457 name=_name__(name, name__=normal_))

1458

1459

1460 def _2n_xyz(name, sa, ca, sb, cb): # name always **name

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

1462 '''

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

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

1465 return Vector3Tuple(ca * cb, ca * sb, sa, **name)

1466

1467

1468 def n_xyz2latlon(x, y, z, **name):

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

1470

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

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

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

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

1475

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

1477

1478 @see: Function L{n_xyz2philam}.

1479 '''

1480 return LatLon2Tuple(atan2d(z, hypot(x, y)), atan2d(y, x), **name)

1481

1482

1483 def n_xyz2philam(x, y, z, **name):

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

1485

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

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

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

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

1490

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

1492

1493 @see: Function L{n_xyz2latlon}.

1494 '''

1495 return PhiLam2Tuple(atan2(z, hypot(x, y)), atan2(y, x), **name)

1496

1497

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

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

1500 '''

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

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

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

1504

1505

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

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

1508

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

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

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

1512

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

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

1515

1516 @see: Function L{opposing_}.

1517 '''

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

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

1520

1521

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

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

1524

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

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

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

1528

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

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

1531

1532 @see: Function L{opposing}.

1533 '''

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

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

1536

1537

1538 def philam2n_xyz(phi, lam, **name):

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

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

1541

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

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

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

1545

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

1547

1548 @see: Function L{latlon2n_xyz}.

1549

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

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

1552 '''

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

1554

1555

1556 def _Propy(func, nargs, kwds):

1557 '''(INTERNAL) Helper for the C{frechet.[-]Frechet**} and

1558 C{hausdorff.[-]Hausdorff*} classes.

1559 '''

1560 try:

1561 _xcallable(distance=func)

1562 # assert _args_kwds_count2(func)[0] == nargs + int(ismethod(func))

1563 _ = func(*_0_0s(nargs), **kwds)

1564 except Exception as x:

1565 t = unstr(func, **kwds)

1566 raise _TypeError(t, cause=x)

1567 return func

1568

1569

1570 def _radical2(d, r1, r2, **name): # 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 n = _name__(name, name__=radical2)

1575 return Radical2Tuple(max(_0_0, min(_1_0, r)), r * d, name=n)

1576

1577

1578 def radical2(distance, radius1, radius2, **name):

1579 '''Compute the I{radical ratio} and I{radical line} of two

1580 U{intersecting circles<https://MathWorld.Wolfram.com/

1581 Circle-CircleIntersection.html>}.

1582

1583 The I{radical line} is perpendicular to the axis thru the

1584 centers of the circles at C{(0, 0)} and C{(B{distance}, 0)}.

1585

1586 @arg distance: Distance between the circle centers (C{scalar}).

1587 @arg radius1: Radius of the first circle (C{scalar}).

1588 @arg radius2: Radius of the second circle (C{scalar}).

1589 @kwarg name: Optional C{B{name}=NN} (C{str}).

1590

1591 @return: A L{Radical2Tuple}C{(ratio, xline)} where C{0.0 <=

1592 ratio <= 1.0} and C{xline} is along the B{C{distance}}.

1593

1594 @raise IntersectionError: The B{C{distance}} exceeds the sum

1595 of B{C{radius1}} and B{C{radius2}}.

1596

1597 @raise UnitError: Invalid B{C{distance}}, B{C{radius1}} or

1598 B{C{radius2}}.

1599

1600 @see: U{Circle-Circle Intersection

1601 <https://MathWorld.Wolfram.com/Circle-CircleIntersection.html>}.

1602 '''

1603 d = Distance_(distance, low=_0_0)

1604 r1 = Radius_(radius1=radius1)

1605 r2 = Radius_(radius2=radius2)

1606 if d > (r1 + r2):

1607 raise IntersectionError(distance=d, radius1=r1, radius2=r2,

1608 txt=_too_(_distant_))

1609 return _radical2(d, r1, r2, **name) if d > EPS0 else \

1610 Radical2Tuple(_0_5, _0_0, **name)

1611

1612

1613 class Radical2Tuple(_NamedTuple):

1614 '''2-Tuple C{(ratio, xline)} of the I{radical} C{ratio} and

1615 I{radical} C{xline}, both C{scalar} and C{0.0 <= ratio <= 1.0}

1616 '''

1617 _Names_ = (_ratio_, _xline_)

1618 _Units_ = ( Scalar, Scalar)

1619

1620

1621 def _radistance(inst):

1622 '''(INTERNAL) Helper for the L{frechet._FrechetMeterRadians}

1623 and L{hausdorff._HausdorffMeterRedians} classes.

1624 '''

1625 wrap_, kwds_ = _xkwds_pop2(inst._kwds, wrap=False)

1626 func_ = inst._func_

1627 try: # calling lower-overhead C{func_}

1628 func_(0, _0_25, _0_5, **kwds_)

1629 wrap_ = _Wrap._philamop(wrap_)

1630 except TypeError:

1631 return inst.distance

1632

1633 def _philam(p):

1634 try:

1635 return p.phi, p.lam

1636 except AttributeError: # no .phi or .lam

1637 return radians(p.lat), radians(p.lon)

1638

1639 def _func_wrap(point1, point2):

1640 phi1, lam1 = wrap_(*_philam(point1))

1641 phi2, lam2 = wrap_(*_philam(point2))

1642 return func_(phi2, phi1, lam2 - lam1, **kwds_)

1643

1644 inst._units = inst._units_

1645 return _func_wrap

1646

1647

1648 def _scale_deg(lat1, lat2): # degrees

1649 # scale factor cos(mean of lats) for delta lon

1650 m = fabs(lat1 + lat2) * _0_5

1651 return cos(radians(m)) if m < 90 else _0_0

1652

1653

1654 def _scale_rad(phi1, phi2): # radians, by .frechet, .hausdorff, .heights

1655 # scale factor cos(mean of phis) for delta lam

1656 m = fabs(phi1 + phi2) * _0_5

1657 return cos(m) if m < PI_2 else _0_0

1658

1659

1660 def _sincosa6(phi2, phi1, lam21): # [4] in cosineLaw

1661 '''(INTERNAL) C{sin}es, C{cos}ines and C{acos}ine.

1662 '''

1663 s2, c2, s1, c1, _, c21 = sincos2_(phi2, phi1, lam21)

1664 return s2, c2, s1, c1, acos1(s1 * s2 + c1 * c2 * c21), c21

1665

1666

1667 def thomas(lat1, lon1, lat2, lon2, datum=_WGS84, wrap=False):

1668 '''Compute the distance between two (ellipsoidal) points using

1669 U{Thomas'<https://apps.DTIC.mil/dtic/tr/fulltext/u2/703541.pdf>}

1670 formula.

1671

1672 @arg lat1: Start latitude (C{degrees}).

1673 @arg lon1: Start longitude (C{degrees}).

1674 @arg lat2: End latitude (C{degrees}).

1675 @arg lon2: End longitude (C{degrees}).

1676 @kwarg datum: Datum (L{Datum}) or ellipsoid (L{Ellipsoid},

1677 L{Ellipsoid2} or L{a_f2Tuple}) to use.

1678 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll

1679 B{C{lat2}} and B{C{lon2}} (C{bool}).

1680

1681 @return: Distance (C{meter}, same units as the B{C{datum}}'s

1682 ellipsoid axes).

1683

1684 @raise TypeError: Invalid B{C{datum}}.

1685

1686 @see: Functions L{thomas_}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

1687 L{cosineLaw}, L{equirectangular}, L{euclidean}, L{flatLocal}/L{hubeny},

1688 L{flatPolar}, L{haversine}, L{vincentys} and method L{Ellipsoid.distance2}.

1689 '''

1690 return _dE(thomas_, datum, wrap, lat1, lon1, lat2, lon2)

1691

1692

1693 def thomas_(phi2, phi1, lam21, datum=_WGS84):

1694 '''Compute the I{angular} distance between two (ellipsoidal) points using

1695 U{Thomas'<https://apps.DTIC.mil/dtic/tr/fulltext/u2/703541.pdf>}

1696 formula.

1697

1698 @arg phi2: End latitude (C{radians}).

1699 @arg phi1: Start latitude (C{radians}).

1700 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).

1701 @kwarg datum: Datum or ellipsoid to use (L{Datum}, L{Ellipsoid},

1702 L{Ellipsoid2} or L{a_f2Tuple}).

1703

1704 @return: Angular distance (C{radians}).

1705

1706 @raise TypeError: Invalid B{C{datum}}.

1707

1708 @see: Functions L{thomas}, L{cosineAndoyerLambert_},

1709 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

1710 L{euclidean_}, L{flatLocal_}/L{hubeny_}, L{flatPolar_},

1711 L{haversine_} and L{vincentys_} and U{Geodesy-PHP

1712 <https://GitHub.com/jtejido/geodesy-php/blob/master/src/Geodesy/

1713 Distance/ThomasFormula.php>}.

1714 '''

1715 s2, c2, s1, c1, r, _ = _sincosa6(phi2, phi1, lam21)

1716 if r and isnon0(c1) and isnon0(c2):

1717 E = _ellipsoidal(datum, thomas_)

1718 if E.f:

1719 r1 = atan2(E.b_a * s1, c1)

1720 r2 = atan2(E.b_a * s2, c2)

1721

1722 j = (r2 + r1) * _0_5

1723 k = (r2 - r1) * _0_5

1724 sj, cj, sk, ck, h, _ = sincos2_(j, k, lam21 * _0_5)

1725

1726 h = fsumf_(sk**2, (ck * h)**2, -(sj * h)**2)

1727 u = _1_0 - h

1728 if isnon0(u) and isnon0(h):

1729 r = atan(sqrt0(h / u)) * 2 # == acos(1 - 2 * h)

1730 sr, cr = sincos2(r)

1731 if isnon0(sr):

1732 u = 2 * (sj * ck)**2 / u

1733 h = 2 * (sk * cj)**2 / h

1734 x = u + h

1735 y = u - h

1736

1737 s = r / sr

1738 e = 4 * s**2

1739 d = 2 * cr

1740 a = e * d

1741 b = 2 * r

1742 c = s - (a - d) * _0_5

1743 f = E.f * _0_25

1744

1745 t = fsumf_(a * x, -b * y, c * x**2, -d * y**2, e * x * y)

1746 r -= fsumf_(s * x, -y, -t * f * _0_25) * f * sr

1747 return r

1748

1749

1750 def vincentys(lat1, lon1, lat2, lon2, radius=R_M, wrap=False):

1751 '''Compute the distance between two (spherical) points using

1752 U{Vincenty's<https://WikiPedia.org/wiki/Great-circle_distance>}

1753 spherical formula.

1754

1755 @arg lat1: Start latitude (C{degrees}).

1756 @arg lon1: Start longitude (C{degrees}).

1757 @arg lat2: End latitude (C{degrees}).

1758 @arg lon2: End longitude (C{degrees}).

1759 @kwarg radius: Mean earth radius (C{meter}), datum (L{Datum})

1760 or ellipsoid (L{Ellipsoid}, L{Ellipsoid2} or

1761 L{a_f2Tuple}) to use.

1762 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll

1763 B{C{lat2}} and B{C{lon2}} (C{bool}).

1764

1765 @return: Distance (C{meter}, same units as B{C{radius}}).

1766

1767 @raise UnitError: Invalid B{C{radius}}.

1768

1769 @see: Functions L{vincentys_}, L{cosineAndoyerLambert},

1770 L{cosineForsytheAndoyerLambert},L{cosineLaw}, L{equirectangular},

1771 L{euclidean}, L{flatLocal}/L{hubeny}, L{flatPolar},

1772 L{haversine} and L{thomas} and methods L{Ellipsoid.distance2},

1773 C{LatLon.distanceTo*} and C{LatLon.equirectangularTo}.

1774

1775 @note: See note at function L{vincentys_}.

1776 '''

1777 return _dS(vincentys_, radius, wrap, lat1, lon1, lat2, lon2)

1778

1779

1780 def vincentys_(phi2, phi1, lam21):

1781 '''Compute the I{angular} distance between two (spherical) points using

1782 U{Vincenty's<https://WikiPedia.org/wiki/Great-circle_distance>}

1783 spherical formula.

1784

1785 @arg phi2: End latitude (C{radians}).

1786 @arg phi1: Start latitude (C{radians}).

1787 @arg lam21: Longitudinal delta, M{end-start} (C{radians}).

1788

1789 @return: Angular distance (C{radians}).

1790

1791 @see: Functions L{vincentys}, L{cosineAndoyerLambert_},

1792 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

1793 L{euclidean_}, L{flatLocal_}/L{hubeny_}, L{flatPolar_},

1794 L{haversine_} and L{thomas_}.

1795

1796 @note: Functions L{vincentys_}, L{haversine_} and L{cosineLaw_}

1797 produce equivalent results, but L{vincentys_} is suitable

1798 for antipodal points and slightly more expensive (M{3 cos,

1799 3 sin, 1 hypot, 1 atan2, 6 mul, 2 add}) than L{haversine_}

1800 (M{2 cos, 2 sin, 2 sqrt, 1 atan2, 5 mul, 1 add}) and

1801 L{cosineLaw_} (M{3 cos, 3 sin, 1 acos, 3 mul, 1 add}).

1802 '''

1803 s1, c1, s2, c2, s21, c21 = sincos2_(phi1, phi2, lam21)

1804

1805 c = c2 * c21

1806 x = s1 * s2 + c1 * c

1807 y = c1 * s2 - s1 * c

1808 return atan2(hypot(c2 * s21, y), x)

1809

1810# **) MIT License

1811#

1812# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.

1813#

1814# Permission is hereby granted, free of charge, to any person obtaining a

1815# copy of this software and associated documentation files (the "Software"),

1816# to deal in the Software without restriction, including without limitation

1817# the rights to use, copy, modify, merge, publish, distribute, sublicense,

1818# and/or sell copies of the Software, and to permit persons to whom the

1819# Software is furnished to do so, subject to the following conditions:

1820#

1821# The above copyright notice and this permission notice shall be included

1822# in all copies or substantial portions of the Software.

1823#

1824# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS

1825# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

1826# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL

1827# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR

1828# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,

1829# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR

1830# OTHER DEALINGS IN THE SOFTWARE.