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.10.14'

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 # ellipsoidalBaseDI

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,

1235 LatLon=None, height=0, wrap=False)

1236 if isinstance(t, Intersection3Tuple): # ellipsoidal

1237 t, _, _ = t

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

1239 return t

1240

1241

1242 def intersections2(lat1, lon1, radius1,

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

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

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

1246

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

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

1249

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

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

1252 in C{meter} or ...

1253

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

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

1256 is installed, otherwise ...

1257

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

1259

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

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

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

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

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

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

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

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

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

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

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

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

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

1273

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

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

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

1277

1278 @raise IntersectionError: Concentric, antipodal, invalid or

1279 non-intersecting circles or no

1280 convergence.

1281

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

1283

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

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

1286 '''

1287 r1 = Radius_(radius1=radius1)

1288 r2 = Radius_(radius2=radius2)

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

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

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

1292 if d is None:

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

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

1295

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

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

1298

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

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

1301 Vector=_V2T)

1302 else:

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

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

1305

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

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

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

1309 return t

1310

1311

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

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

1314 opposite sides of the earth.

1315

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

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

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

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

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

1321

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

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

1324

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

1326 '''

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

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

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

1330

1331

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

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

1334 opposite sides of the earth.

1335

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

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

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

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

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

1341

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

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

1344

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

1346 '''

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

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

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

1350

1351

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

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

1354 '''

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

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

1357

1358

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

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

1361 '''

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

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

1364

1365

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

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

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

1369

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

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

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

1373

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

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

1376

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

1378 '''

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

1380

1381

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

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

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

1385

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

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

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

1389

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

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

1392

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

1394 '''

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

1396

1397

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

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

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

1401

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

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

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

1405

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

1407

1408 @see: Function L{philam2n_xyz}.

1409

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

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

1412 '''

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

1414

1415

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

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

1418 '''

1419 if fabs(b) > n:

1420 b = remainder(b, n2)

1421 if fabs(a) > n_2:

1422 r = remainder(a, n)

1423 if r != a:

1424 a = -r

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

1426 return float0_(a, b)

1427

1428

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

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

1431

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

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

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

1435

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

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

1438

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

1440 '''

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

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

1443

1444

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

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

1447

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

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

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

1451

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

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

1454

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

1456 '''

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

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

1459

1460

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

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

1463 '''

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

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

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

1467

1468

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

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

1471

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

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

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

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

1476

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

1478

1479 @see: Function L{n_xyz2philam}.

1480 '''

1481 return LatLon2Tuple(atan2d(z, hypot(x, y)), atan2d(y, x), **name)

1482

1483

1484 def n_xyz2philam(x, y, z, **name):

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

1486

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

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

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

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

1491

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

1493

1494 @see: Function L{n_xyz2latlon}.

1495 '''

1496 return PhiLam2Tuple(atan2(z, hypot(x, y)), atan2(y, x), **name)

1497

1498

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

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

1501 '''

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

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

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

1505

1506

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

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

1509

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

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

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

1513

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

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

1516

1517 @see: Function L{opposing_}.

1518 '''

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

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

1521

1522

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

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

1525

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

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

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

1529

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

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

1532

1533 @see: Function L{opposing}.

1534 '''

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

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

1537

1538

1539 def philam2n_xyz(phi, lam, **name):

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

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

1542

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

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

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

1546

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

1548

1549 @see: Function L{latlon2n_xyz}.

1550

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

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

1553 '''

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

1555

1556

1557 def _Propy(func, nargs, kwds):

1558 '''(INTERNAL) Helper for the C{frechet.[-]Frechet**} and

1559 C{hausdorff.[-]Hausdorff*} classes.

1560 '''

1561 try:

1562 _xcallable(distance=func)

1563 # assert _args_kwds_count2(func)[0] == nargs + int(ismethod(func))

1564 _ = func(*_0_0s(nargs), **kwds)

1565 except Exception as x:

1566 t = unstr(func, **kwds)

1567 raise _TypeError(t, cause=x)

1568 return func

1569

1570

1571 def _radical2(d, r1, r2, **name): # in .ellipsoidalBaseDI, .sphericalTrigonometry, .vector3d

1572 # (INTERNAL) See C{radical2} below

1573 # assert d > EPS0

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

1575 n = _name__(name, name__=radical2)

1576 return Radical2Tuple(max(_0_0, min(_1_0, r)), r * d, name=n)

1577

1578

1579 def radical2(distance, radius1, radius2, **name):

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

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

1582 Circle-CircleIntersection.html>}.

1583

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

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

1586

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

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

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

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

1591

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

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

1594

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

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

1597

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

1599 B{C{radius2}}.

1600

1601 @see: U{Circle-Circle Intersection

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

1603 '''

1604 d = Distance_(distance, low=_0_0)

1605 r1 = Radius_(radius1=radius1)

1606 r2 = Radius_(radius2=radius2)

1607 if d > (r1 + r2):

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

1609 txt=_too_(_distant_))

1610 return _radical2(d, r1, r2, **name) if d > EPS0 else \

1611 Radical2Tuple(_0_5, _0_0, **name)

1612

1613

1614 class Radical2Tuple(_NamedTuple):

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

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

1617 '''

1618 _Names_ = (_ratio_, _xline_)

1619 _Units_ = ( Scalar, Scalar)

1620

1621

1622 def _radistance(inst):

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

1624 and L{hausdorff._HausdorffMeterRedians} classes.

1625 '''

1626 wrap_, kwds_ = _xkwds_pop2(inst._kwds, wrap=False)

1627 func_ = inst._func_

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

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

1630 wrap_ = _Wrap._philamop(wrap_)

1631 except TypeError:

1632 return inst.distance

1633

1634 def _philam(p):

1635 try:

1636 return p.phi, p.lam

1637 except AttributeError: # no .phi or .lam

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

1639

1640 def _func_wrap(point1, point2):

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

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

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

1644

1645 inst._units = inst._units_

1646 return _func_wrap

1647

1648

1649 def _scale_deg(lat1, lat2): # degrees

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

1651 m = fabs(lat1 + lat2) * _0_5

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

1653

1654

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

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

1657 m = fabs(phi1 + phi2) * _0_5

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

1659

1660

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

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

1663 '''

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

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

1666

1667

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

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

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

1671 formula.

1672

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

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

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

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

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

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

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

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

1681

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

1683 ellipsoid axes).

1684

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

1686

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

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

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

1690 '''

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

1692

1693

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

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

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

1697 formula.

1698

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

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

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

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

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

1704

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

1706

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

1708

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

1710 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

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

1712 L{haversine_} and L{vincentys_} and U{Geodesy-PHP

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

1714 Distance/ThomasFormula.php>}.

1715 '''

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

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

1718 E = _ellipsoidal(datum, thomas_)

1719 if E.f:

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

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

1722

1723 j = (r2 + r1) * _0_5

1724 k = (r2 - r1) * _0_5

1725 sj, cj, sk, ck, h, _ = sincos2_(j, k, lam21 * _0_5)

1726

1727 h = fsumf_(sk**2, (ck * h)**2, -(sj * h)**2)

1728 u = _1_0 - h

1729 if isnon0(u) and isnon0(h):

1730 r = atan(sqrt0(h / u)) * 2 # == acos(1 - 2 * h)

1731 sr, cr = sincos2(r)

1732 if isnon0(sr):

1733 u = 2 * (sj * ck)**2 / u

1734 h = 2 * (sk * cj)**2 / h

1735 x = u + h

1736 y = u - h

1737

1738 s = r / sr

1739 e = 4 * s**2

1740 d = 2 * cr

1741 a = e * d

1742 b = 2 * r

1743 c = s - (a - d) * _0_5

1744 f = E.f * _0_25

1745

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

1747 r -= fsumf_(s * x, -y, -t * f * _0_25) * f * sr

1748 return r

1749

1750

1751 def vincentys(lat1, lon1, lat2, lon2, radius=R_M, wrap=False):

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

1753 U{Vincenty's<https://WikiPedia.org/wiki/Great-circle_distance>}

1754 spherical formula.

1755

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

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

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

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

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

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

1762 L{a_f2Tuple}) to use.

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

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

1765

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

1767

1768 @raise UnitError: Invalid B{C{radius}}.

1769

1770 @see: Functions L{vincentys_}, L{cosineAndoyerLambert},

1771 L{cosineForsytheAndoyerLambert},L{cosineLaw}, L{equirectangular},

1772 L{euclidean}, L{flatLocal}/L{hubeny}, L{flatPolar},

1773 L{haversine} and L{thomas} and methods L{Ellipsoid.distance2},

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

1775

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

1777 '''

1778 return _dS(vincentys_, radius, wrap, lat1, lon1, lat2, lon2)

1779

1780

1781 def vincentys_(phi2, phi1, lam21):

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

1783 U{Vincenty's<https://WikiPedia.org/wiki/Great-circle_distance>}

1784 spherical formula.

1785

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

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

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

1789

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

1791

1792 @see: Functions L{vincentys}, L{cosineAndoyerLambert_},

1793 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

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

1795 L{haversine_} and L{thomas_}.

1796

1797 @note: Functions L{vincentys_}, L{haversine_} and L{cosineLaw_}

1798 produce equivalent results, but L{vincentys_} is suitable

1799 for antipodal points and slightly more expensive (M{3 cos,

1800 3 sin, 1 hypot, 1 atan2, 6 mul, 2 add}) than L{haversine_}

1801 (M{2 cos, 2 sin, 2 sqrt, 1 atan2, 5 mul, 1 add}) and

1802 L{cosineLaw_} (M{3 cos, 3 sin, 1 acos, 3 mul, 1 add}).

1803 '''

1804 s1, c1, s2, c2, s21, c21 = sincos2_(phi1, phi2, lam21)

1805

1806 c = c2 * c21

1807 x = s1 * s2 + c1 * c

1808 y = c1 * s2 - s1 * c

1809 return atan2(hypot(c2 * s21, y), x)

1810

1811# **) MIT License

1812#

1813# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.

1814#

1815# Permission is hereby granted, free of charge, to any person obtaining a

1816# copy of this software and associated documentation files (the "Software"),

1817# to deal in the Software without restriction, including without limitation

1818# the rights to use, copy, modify, merge, publish, distribute, sublicense,

1819# and/or sell copies of the Software, and to permit persons to whom the

1820# Software is furnished to do so, subject to the following conditions:

1821#

1822# The above copyright notice and this permission notice shall be included

1823# in all copies or substantial portions of the Software.

1824#

1825# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS

1826# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

1827# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL

1828# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR

1829# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,

1830# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR

1831# OTHER DEALINGS IN THE SOFTWARE.