1

2# -*- coding: utf-8 -*-

3

4 u'''Formulary of basic geodesy functions and approximations.

5'''

6# make sure int/int division yields float quotient, see .basics

7 from __future__ import division as _; del _ # PYCHOK semicolon

8

9# from pygeodesy.basics import isscalar # from .fsums

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

11 _umod_PI2, float0, isnon0, remainder, _0_0, \

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

13 _4_0, _32_0, _90_0, _180_0, _360_0

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

15 _mean_radius, _spherical_datum, _WGS84

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

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

18 limiterrors, _ValueError, _xError

19 from pygeodesy.fmath import Fdot, euclid, fdot, hypot, hypot2, sqrt0

20 from pygeodesy.fsums import fsum_, isscalar, unstr

21 from pygeodesy.interns import NN, _distant_, _inside_, _near_, _null_, \

22 _opposite_, _outside_, _too_

23 from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS

24 from pygeodesy.named import _NamedTuple, _xnamed

25 from pygeodesy.namedTuples import Bearing2Tuple, Distance4Tuple, \

26 Intersection3Tuple, LatLon2Tuple, \

27 PhiLam2Tuple, Vector3Tuple

28# from pygeodesy.streprs import unstr # from .fsums

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

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

31 Radius, Radius_, Scalar, _100km

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

33 sincos2, sincos2_, sincos2d_, unroll180, unrollPI

34

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

36

37__all__ = _ALL_LAZY.formy

38__version__ = '23.04.12'

39

40_ratio_ = 'ratio'

41_xline_ = 'xline'

42

43

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

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

46 '''

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

48 if r == a:

49 r = -r

50 b += n

51 if fabs(b) > n:

52 b = remainder(b, n2)

53 return float0(r, b)

54

55

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

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

58 to a given point in C{degrees}.

59

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

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

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

63

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

65

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

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

68 '''

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

70

71

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

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

74 to a given point in C{radians}.

75

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

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

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

79

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

81

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

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

84 '''

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

86

87

88 def _area_or_(excess_, lat1, lat2, radius, d_lon, unused):

89 '''(INTERNAL) Helper for area and spherical excess.

90 '''

91 r = excess_(Phi_(lat2=lat2),

92 Phi_(lat1=lat1), radians(d_lon))

93 if radius:

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

95 return r

96

97

98 def bearing(lat1, lon1, lat2, lon2, **options):

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

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

101

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

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

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

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

106 @kwarg options: Optional keyword arguments for function

107 L{pygeodesy.bearing_}.

108

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

110 zero if start and end point coincide.

111 '''

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

113 Phi_(lat2=lat2), Lam_(lon2=lon2), **options)

114 return degrees(r)

115

116

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

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

119 between a (spherical) start and end point.

120

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

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

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

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

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

126 @kwarg wrap: Wrap and L{pygeodesy.unrollPI} longitudes (C{bool}).

127

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

129 and end point coincide.

130

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

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

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

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

135 '''

136 if final: # swap plus PI

137 phi1, lam1, phi2, lam2 = phi2, lam2, phi1, lam1

138 r = PI3

139 else:

140 r = PI2

141

142 db, _ = unrollPI(lam1, lam2, wrap=wrap)

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 a1, b1 = p1.philam

159 a2, b2 = p2.philam

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

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

162 name=_bearingTo2.__name__)

163

164

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

166 '''Return the angle from North for the direction vector

167 M{(lon2 - lon1, lat2 - lat1)} between two points.

168

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

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

171

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

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

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

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

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

177 mean latitude (C{bool}).

178 @kwarg wrap: Wrap and L{pygeodesy.unroll180} longitudes (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, _ = unroll180(lon1, lon2, wrap=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

195 U{Andoyer-Lambert correction<https://navlib.net/wp-content/uploads/

196 2013/10/admiralty-manual-of-navigation-vol-1-1964-english501c.pdf>} of the

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

198 fromula.

199

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

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

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

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

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

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

206 @kwarg wrap: Wrap and L{pygeodesy.unroll180} longitudes (C{bool}).

207

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

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

210

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

212

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

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

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

216 L{Ellipsoid.distance2}.

217 '''

218 return _distanceToE(cosineAndoyerLambert_, lat1, lat2, datum,

219 *unroll180(lon1, lon2, wrap=wrap))

220

221

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

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

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

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

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

227 fromula.

228

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

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

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

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

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

234

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

236

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

238

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

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

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

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

243 Distance/AndoyerLambert.php>}.

244 '''

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

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

247 E = _ellipsoidal(datum, cosineAndoyerLambert_)

248 if E.f: # ellipsoidal

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

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

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

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

253 if r:

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

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

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

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

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

259 return r

260

261

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

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

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

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

266 formula.

267

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

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

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

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

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

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

274 @kwarg wrap: Wrap and L{pygeodesy.unroll180} longitudes (C{bool}).

275

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

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

278

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

280

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

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

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

284 L{Ellipsoid.distance2}.

285 '''

286 return _distanceToE(cosineForsytheAndoyerLambert_, lat1, lat2, datum,

287 *unroll180(lon1, lon2, wrap=wrap))

288

289

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

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

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

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

294 formula.

295

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

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

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

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

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

301

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

303

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

305

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

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

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

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

310 Distance/ForsytheCorrection.php>}.

311 '''

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

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

314 E = _ellipsoidal(datum, cosineForsytheAndoyerLambert_)

315 if E.f: # ellipsoidal

316 sr, cr, s2r, _ = sincos2_(r, r * _2_0)

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

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

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

320 x = s + t

321 y = s - t

322

323 s = 8 * r**2 / sr

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

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

326 b = -2 * d

327 e = 30 * s2r

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

329

330 t = fsum_( a * x, b * y, -c * x**2, d * x * y, e * y**2)

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

332 return r

333

334

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

336 '''Compute the distance between two points using the

337 U{spherical Law of Cosines

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

339 formula.

340

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

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

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

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

345 @kwarg radius: Mean earth radius, ellipsoid or datum (C{meter},

346 L{Ellipsoid}, L{Ellipsoid2}, L{Datum} or L{a_f2Tuple}).

347 @kwarg wrap: Wrap and L{pygeodesy.unroll180} longitudes (C{bool}).

348

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

350 ellipsoid or datum axes).

351

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

353

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

355 L{cosineForsytheAndoyerLambert}, L{equirectangular}, L{euclidean},

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

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

358

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

360 '''

361 return _distanceToS(cosineLaw_, lat1, lat2, radius,

362 *unroll180(lon1, lon2, wrap=wrap))

363

364

365 def cosineLaw_(phi2, phi1, lam21):

366 '''Compute the I{angular} distance between two points using the

367 U{spherical Law of Cosines

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

369 formula.

370

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

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

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

374

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

376

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

378 L{cosineForsytheAndoyerLambert_}, L{equirectangular_},

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

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

381

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

383 '''

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

385

386

387 def _distanceToE(func_, lat1, lat2, earth, d_lon, unused):

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

389 '''

390 E = _ellipsoidal(earth, func_)

391 r = func_(Phi_(lat2=lat2),

392 Phi_(lat1=lat1), radians(d_lon), datum=E)

393 return r * E.a

394

395

396 def _distanceToS(func_, lat1, lat2, earth, d_lon, unused, **adjust):

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

398 '''

399 r = func_(Phi_(lat2=lat2),

400 Phi_(lat1=lat1), radians(d_lon), **adjust)

401 return r * _mean_radius(earth, lat1, lat2)

402

403

404 def _ellipsoidal(earth, where):

405 '''(INTERNAL) Helper for distances.

406 '''

407 return earth if isinstance(earth, Ellipsoid) else (

408 earth if isinstance(earth, Datum) else

409 _ellipsoidal_datum(earth, name=where.__name__)).ellipsoid # PYCHOK indent

410

411

412 def equirectangular(lat1, lon1, lat2, lon2, radius=R_M, **options):

413 '''Compute the distance between two points using

414 the U{Equirectangular Approximation / Projection

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

416

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

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

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

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

421 @kwarg radius: Mean earth radius, ellipsoid or datum

422 (C{meter}, L{Ellipsoid}, L{Ellipsoid2},

423 L{Datum} or L{a_f2Tuple}).

424 @kwarg options: Optional keyword arguments for function

425 L{equirectangular_}.

426

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

428 the ellipsoid or datum axes).

429

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

431

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

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

434 approximate or accurate distance functions.

435 '''

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

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

438 **options).distance2) # PYCHOK 4 vs 2-3

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

440

441

442 def equirectangular_(lat1, lon1, lat2, lon2,

443 adjust=True, limit=45, wrap=False):

444 '''Compute the distance between two points using

445 the U{Equirectangular Approximation / Projection

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

447

448 This approximation is valid for short distance of several

449 hundred Km or Miles, see the B{C{limit}} keyword argument and

450 the L{LimitError}.

451

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

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

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

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

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

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

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

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

460 @kwarg wrap: Wrap and L{pygeodesy.unroll180} longitudes (C{bool}).

461

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

463 unroll_lon2)}.

464

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

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

467 set to C{True}.

468

469 @see: U{Local, flat earth approximation

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

471 L{equirectangular}, L{cosineAndoyerLambert},

472 L{cosineForsytheAndoyerLambert}, L{cosineLaw}, L{euclidean},

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

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

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

476 '''

477 d_lat = lat2 - lat1

478 d_lon, ulon2 = unroll180(lon1, lon2, wrap=wrap)

479

480 if limit and limit > 0 and limiterrors() and (fabs(d_lat) > limit or

481 fabs(d_lon) > limit):

482 t = unstr(equirectangular_, lat1, lon1, lat2, lon2, limit=limit)

483 raise LimitError('delta exceeds limit', txt=t)

484

485 if adjust: # scale delta lon

486 d_lon *= _scale_deg(lat1, lat2)

487

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

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

490

491

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

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

494

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

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

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

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

499 @kwarg radius: Mean earth radius, ellipsoid or datum (C{meter},

500 L{Ellipsoid}, L{Ellipsoid2}, L{Datum} or L{a_f2Tuple}).

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

502 mean latitude (C{bool}).

503 @kwarg wrap: Wrap and L{pygeodesy.unroll180} longitudes (C{bool}).

504

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

506 ellipsoid or datum axes).

507

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

509

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

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

512 L{euclidean_}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

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

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

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

516 '''

517 return _distanceToS(euclidean_, lat1, lat2, radius,

518 *unroll180(lon1, lon2, wrap=wrap),

519 adjust=adjust)

520

521

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

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

524 (spherical) points.

525

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

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

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

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

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

531

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

533

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

535 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_}, L{equirectangular_},

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

537 and L{vincentys_}.

538 '''

539 if adjust:

540 lam21 *= _scale_rad(phi2, phi1)

541 return euclid(phi2 - phi1, lam21)

542

543

544 def excessAbc_(A, b, c):

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

546 from two sides and the included angle.

547

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

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

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

551

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

553

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

555

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

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

558 '''

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

560 Radians_(c=c) * _0_5)

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

562

563

564 def excessGirard_(A, B, C):

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

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

567 formula.

568

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

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

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

572

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

574

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

576

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

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

579 '''

580 return Radians(Girard=fsum_(Radians_(A=A),

581 Radians_(B=B),

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

583

584

585 def excessLHuilier_(a, b, c):

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

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

588 Theorem.

589

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

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

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

593

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

595

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

597

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

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

600 '''

601 a = Radians_(a=a)

602 b = Radians_(b=b)

603 c = Radians_(c=c)

604

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

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

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

608 return Radians(LHuilier=r * _4_0)

609

610

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

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

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

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

615 method.

616

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

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

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

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

621 @kwarg radius: Mean earth radius, ellipsoid or datum (C{meter}, L{Ellipsoid},

622 L{Ellipsoid2}, L{Datum} or L{a_f2Tuple}) or C{None}.

623 @kwarg wrap: Wrap and L{pygeodesy.unroll180} longitudes (C{bool}).

624

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

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

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

628

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

630

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

632

633 @raise ValueError: Semi-circular longitudinal delta.

634

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

636 '''

637 return _area_or_(excessKarney_, lat1, lat2, radius,

638 *unroll180(lon1, lon2, wrap=wrap))

639

640

641 def excessKarney_(phi2, phi1, lam21):

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

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

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

645 method.

646

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

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

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

650

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

652

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

654

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

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

657 '''

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

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

660 #

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

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

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

664 #

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

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

667 t2 = tan_2(phi2)

668 t1 = tan_2(phi1)

669 t = tan_2(lam21, lam21=None)

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

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

672

673

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

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

676#

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

678#

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

680#

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

682#

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

684#

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

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

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

688#

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

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

691#

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

693# Lambertian(phi2)) / 2)

694#

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

696# inverse Gudermannian) function

697#

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

699#

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

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

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

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

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

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

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

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

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

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

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

711# - Charles Karney

712

713

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

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

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

717

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

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

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

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

722 @kwarg radius: Mean earth radius, ellipsoid or datum (C{meter},

723 L{Ellipsoid}, L{Ellipsoid2}, L{Datum} or L{a_f2Tuple}) or C{None}.

724 @kwarg wrap: Wrap and L{pygeodesy.unroll180} longitudes (C{bool}).

725

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

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

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

729

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

731

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

733

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

735 '''

736 return _area_or_(excessQuad_, lat1, lat2, radius,

737 *unroll180(lon1, lon2, wrap=wrap))

738

739

740 def excessQuad_(phi2, phi1, lam21):

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

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

743

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

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

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

747

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

749

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

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

752 '''

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

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

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

756

757

758 def flatLocal(lat1, lon1, lat2, lon2, datum=_WGS84, wrap=False):

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

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

761 wiki/Geographical_distance#Ellipsoidal_Earth_projected_to_a_plane>}

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

763

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

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

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

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

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

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

770 @kwarg wrap: Wrap and L{pygeodesy.unroll180} longitudes (C{bool}).

771

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

773 ellipsoid axes).

774

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

776

777 @note: The meridional and prime_vertical radii of curvature

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

779

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

781 L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

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

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

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

785 '''

786 d, _ = unroll180(lon1, lon2, wrap=wrap)

787 return flatLocal_(Phi_(lat2=lat2),

788 Phi_(lat1=lat1), radians(d), datum=datum)

789

790 hubeny = flatLocal # PYCHOK for Karl Hubeny

791

792

793 def flatLocal_(phi2, phi1, lam21, datum=_WGS84):

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

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

796 wiki/Geographical_distance#Ellipsoidal_Earth_projected_to_a_plane>}

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

798

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

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

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

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

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

804

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

806

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

808

809 @note: The meridional and prime_vertical radii of curvature

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

811

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

813 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_}, L{flatPolar_},

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

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

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

817 '''

818 E = _ellipsoidal(datum, flatLocal_)

819 m, n = E.roc2_((phi2 + phi1) * _0_5, scaled=True)

820 return hypot(m * (phi2 - phi1), n * lam21)

821

822 hubeny_ = flatLocal_ # PYCHOK for Karl Hubeny

823

824

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

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

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

828 Geographical_distance#Polar_coordinate_flat-Earth_formula>}

829 formula.

830

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

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

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

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

835 @kwarg radius: Mean earth radius, ellipsoid or datum (C{meter},

836 L{Ellipsoid}, L{Ellipsoid2}, L{Datum} or L{a_f2Tuple}).

837 @kwarg wrap: Wrap and L{pygeodesy.unroll180} longitudes (C{bool}).

838

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

840 ellipsoid or datum axes).

841

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

843

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

845 L{cosineForsytheAndoyerLambert},L{cosineLaw},

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

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

848 L{vincentys}.

849 '''

850 return _distanceToS(flatPolar_, lat1, lat2, radius,

851 *unroll180(lon1, lon2, wrap=wrap))

852

853

854 def flatPolar_(phi2, phi1, lam21):

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

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

857 Geographical_distance#Polar_coordinate_flat-Earth_formula>}

858 formula.

859

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

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

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

863

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

865

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

867 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

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

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

870 '''

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

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

873 if a < b:

874 a, b = b, a

875 if a < EPS0:

876 a = _0_0

877 elif b > 0:

878 b = b / a # /= chokes PyChecker

879 c = b * cos(lam21) * _2_0

880 c = fsum_(_1_0, b**2, -fabs(c))

881 a *= sqrt0(c)

882 return a

883

884

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

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

887 from a Point-Of-View in space.

888

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

890 or L{Vector3d}).

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

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

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

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

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

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

897 point plus C{LatLon} keyword arguments, include

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

899

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

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

902

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

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

905 the earth or points in an opposite direction.

906

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

908

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

910 U{I{Satellite Line-of-Sight Intersection with Earth}<https://StephenHartzell.

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

912 '''

913 def _Error(txt):

914 return IntersectionError(pov=pov, los=los, earth=earth, txt=txt)

915

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

917 _spherical_datum(earth, name=hartzell.__name__)

918 E = D.ellipsoid

919

920 if E.b > E.a: # PYCHOK no cover

921 try:

922 t = _MODS.triaxials

923 r, _ = t._hartzell3d2(pov, los, t.Triaxial_(E.a, E.a, E.b))

924 except Exception as x:

925 raise _Error(str(x))

926 else:

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

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

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

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

931

932 V3 = _MODS.vector3d._otherV3d

933 p3 = V3(pov=pov)

934 u3 = V3(los=los) if los else p3.negate()

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

936

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

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

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

940

941 t = c2, c2, b2

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

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

944 raise _Error(_near_(_null_))

945

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

947 r = fsum_(b2 * w2, c2 * v2, -v2 * z2, vy * wz * 2,

948 c2 * u2, -u2 * z2, -w2 * x2, ux * wz * 2,

949 -w2 * y2, -u2 * y2 * q2, -v2 * x2 * q2, ux * vy * 2 * q2, floats=True)

950 if r > 0:

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

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

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

954

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

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

957 s = fsum_(_1_0, x2 / a2, y2 / b2, z2 / c2, _N_2_0, floats=True) # like _sideOf

958 raise _Error(_outside_ if s > 0 else _inside_)

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

960 raise _Error(_too_(_distant_))

961

962 r = p3.minus(u3.times(d))

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

964

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

966 if LatLon_and_kwds:

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

968 r = c.toLatLon(**LatLon_and_kwds)

969 return r

970

971

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

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

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

975 formula.

976

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

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

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

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

981 @kwarg radius: Mean earth radius, ellipsoid or datum (C{meter},

982 L{Ellipsoid}, L{Ellipsoid2}, L{Datum} or L{a_f2Tuple}).

983 @kwarg wrap: Wrap and L{pygeodesy.unroll180} longitudes (C{bool}).

984

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

986

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

988

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

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

991 L{cosineLaw}, L{cosineAndoyerLambert}, L{cosineForsytheAndoyerLambert},

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

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

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

995

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

997 '''

998 return _distanceToS(haversine_, lat1, lat2, radius,

999 *unroll180(lon1, lon2, wrap=wrap))

1000

1001

1002 def haversine_(phi2, phi1, lam21):

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

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

1005 formula.

1006

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

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

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

1010

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

1012

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

1014 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

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

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

1017

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

1019 '''

1020 def _hsin(rad):

1021 return sin(rad * _0_5)**2

1022

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

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

1025

1026

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

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

1029 traveling along a straight line at a given tilt.

1030

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

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

1033 B{C{radius}}).

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

1035

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

1037

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

1039

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

1041 (U{Shapiro et al. 2009, JTECH

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

1043 and U{Potvin et al. 2012, JTECH

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

1045 '''

1046 r = h = Radius(radius)

1047 d = fabs(Distance(distance))

1048 if d > h:

1049 d, h = h, d

1050

1051 if d > EPS0: # and h > EPS0

1052 d = d / h # /= h chokes PyChecker

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

1054 s = fsum_(_1_0, _2_0 * s * d, d**2)

1055 if s > 0:

1056 return h * sqrt(s) - r

1057

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

1059

1060

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

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

1063 above the (spherical) earth.

1064

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

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

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

1068

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

1070

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

1072

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

1074 '''

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

1076 if min(h, r) < 0:

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

1078

1079 if refraction:

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

1081 else:

1082 d2 = h * fsum_(r, r, h)

1083 return sqrt0(d2)

1084

1085

1086 def _idlmn5(datum, lat1, lon1, lat2, lon2, small, wrap, s):

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

1088 '''

1089 m = Meter_(small=small)

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

1091 if datum is None or euclidean(lat1, lon1, lat2, lon2, radius=R_M,

1092 adjust=True, wrap=wrap) < m:

1093 d, m = None, _MODS.vector3d

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

1095 _, lon2 = unroll180(lon1, lon2, wrap=wrap)

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

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

1098 m = _MODS.sphericalNvector

1099 _i = m.intersection

1100 else:

1101 d = _spherical_datum(datum, name=n)

1102 if d.isSpherical:

1103 m = _MODS.sphericalTrigonometry

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

1105 elif d.isEllipsoidal:

1106 try:

1107 if d.ellipsoid.geodesic:

1108 pass

1109 m = _MODS.ellipsoidalKarney

1110 except ImportError:

1111 m = _MODS.ellipsoidalExact

1112 _i = m._intersections2 if s else m._intersection3 # ellispoidalBaseDi

1113 else:

1114 raise _AssertionError(datum=datum)

1115 return _i, d, lon2, m, n

1116

1117

1118 def intersection2(lat1, lon1, bearing1,

1119 lat2, lon2, bearing2, datum=None, wrap=True, small=_100km):

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

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

1122

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

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

1125

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

1127 or if B{C{datum}} is a C{scalar} representing the earth

1128 radius, conventionally in C{meter} or ...

1129

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

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

1132

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

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

1135 is installed, otherwise ...

1136

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

1138

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

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

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

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

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

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

1145 @kwarg datum: Optional ellipsoidal or spherical datum (L{Datum},

1146 L{Ellipsoid}, L{Ellipsoid2}, L{a_f2Tuple} or

1147 C{scalar} earth radius in C{meter}) or C{None}.

1148 @kwarg wrap: Wrap and unroll longitudes (C{bool}).

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

1150

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

1152 longitude of the intersection point.

1153

1154 @raise IntersectionError: Ambiguous or infinite intersection

1155 or colinear, parallel or otherwise

1156 non-intersecting lines.

1157

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

1159

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

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

1162

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

1164

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

1166 '''

1167 b1, b2 = Bearing(bearing1=bearing1), Bearing(bearing2=bearing2)

1168 try:

1169 _i, d, l2, m, n = _idlmn5(datum, lat1, lon1, lat2, lon2, small, wrap,

1170 False)

1171 if d is None:

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

1173 m.Vector3d(l2, lat2, 0), b2, useZ=False)

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

1175

1176 else:

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

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

1179 if isinstance(t, Intersection3Tuple): # ellipsoidal

1180 t, _, _ = t

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

1182

1183 except (TypeError, ValueError) as x:

1184 raise _xError(x, lat1=lat1, lon1=lon1, bearing1=bearing1,

1185 lat2=lat2, lon2=lon2, bearing2=bearing2,

1186 datum=datum, small=small, wrap=wrap)

1187 return t

1188

1189

1190 def intersections2(lat1, lon1, radius1,

1191 lat2, lon2, radius2, datum=None, wrap=True, small=_100km):

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

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

1194

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

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

1197

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

1199 or if B{C{datum}} is a C{scalar} representing the earth radius,

1200 conventionally in C{meter} or ...

1201

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

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

1204 is installed, otherwise ...

1205

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

1207

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

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

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

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

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

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

1214 @kwarg datum: Optional ellipsoidal or spherical datum (L{Datum},

1215 L{Ellipsoid}, L{Ellipsoid2}, L{a_f2Tuple} or

1216 C{scalar} earth radius in C{meter}, same units as

1217 B{C{radius1}} and B{C{radius2}}) or C{None}.

1218 @kwarg wrap: Wrap and unroll longitudes (C{bool}).

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

1220

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

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

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

1224

1225 @raise IntersectionError: Concentric, antipodal, invalid or

1226 non-intersecting circles or no

1227 convergence.

1228

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

1230

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

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

1233 '''

1234 r1, r2 = Radius_(radius1=radius1), Radius_(radius2=radius2)

1235 try:

1236 _i, d, l2, m, n = _idlmn5(datum, lat1, lon1, lat2, lon2, small, wrap,

1237 True)

1238 if d is None:

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

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

1241

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

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

1244

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

1246 m.Vector3d(l2, lat2, 0), r2, sphere=False,

1247 Vector=_V2T)

1248 else:

1249

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

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

1252

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

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

1255 LatLon=_LL2T, height=0, wrap=wrap)

1256

1257 except (TypeError, ValueError) as x:

1258 raise _xError(x, lat1=lat1, lon1=lon1, radius1=radius1,

1259 lat2=lat2, lon2=lon2, radius2=radius2,

1260 datum=datum, small=small, wrap=wrap)

1261 return t

1262

1263

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

1265 '''Check whether two points are antipodal, on diametrically

1266 opposite sides of the earth.

1267

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

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

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

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

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

1273

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

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

1276

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

1278 '''

1279 return True if (fabs(lat1 + lat2) <= eps and

1280 fabs(lon1 + lon2) <= eps) else \

1281 _MODS.latlonBase._isequalTo(antipode(lat1, lon1),

1282 normal(lat2, lon2), eps=eps)

1283

1284

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

1286 '''Check whether two points are antipodal, on diametrically

1287 opposite sides of the earth.

1288

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

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

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

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

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

1294

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

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

1297

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

1299 '''

1300 return True if (fabs(phi1 + phi2) <= eps and

1301 fabs(lam1 + lam2) <= eps) else \

1302 _MODS.latlonBase._isequalTo_(antipode_(phi1, lam1),

1303 normal_(phi2, lam2), eps=eps)

1304

1305

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

1307 '''Check whether B{C{lat}} I{and} B{C{lon}} are within the I{normal}

1308 range in C{degrees}.

1309

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

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

1312 @kwarg eps: Optional tolerance below C{90} and C{180 degrees}.

1313

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

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

1316

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

1318 '''

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

1320

1321

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

1323 '''Check whether B{C{phi}} I{and} B{C{lam}} are within the I{normal}

1324 range in C{radians}.

1325

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

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

1328 @kwarg eps: Optional tolerance below C{PI/2} and C{PI radians}.

1329

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

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

1332

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

1334 '''

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

1336

1337

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

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

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

1341

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

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

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

1345

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

1347

1348 @see: Function L{philam2n_xyz}.

1349

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

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

1352 '''

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

1354

1355

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

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

1358 '''

1359 if fabs(b) > n:

1360 b = remainder(b, n2)

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

1362 if r != a:

1363 r = -r

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

1365 return float0(r, b)

1366

1367

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

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

1370

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

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

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

1374

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

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

1377

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

1379 '''

1380 return LatLon2Tuple(*_normal2(lat, lon, _90_0, _180_0, _360_0), name=name)

1381

1382

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

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

1385

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

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

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

1389

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

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

1392

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

1394 '''

1395 return PhiLam2Tuple(*_normal2(phi, lam, PI_2, PI, PI2), name=name)

1396

1397

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

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

1400 '''

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

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

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

1404

1405

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

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

1408

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

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

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

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

1413

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

1415

1416 @see: Function L{n_xyz2philam}.

1417 '''

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

1419

1420

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

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

1423

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

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

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

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

1428

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

1430

1431 @see: Function L{n_xyz2latlon}.

1432 '''

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

1434

1435

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

1437 '''(INETNAL) Helper for C{opposing} and C{opposing_}.

1438 '''

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

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

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

1442

1443

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

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

1446

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

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

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

1450

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

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

1453

1454 @see: Function L{opposing_}.

1455 '''

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

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

1458

1459

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

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

1462

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

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

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

1466

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

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

1469

1470 @see: Function L{opposing}.

1471 '''

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

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

1474

1475

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

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

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

1479

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

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

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

1483

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

1485

1486 @see: Function L{latlon2n_xyz}.

1487

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

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

1490 '''

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

1492

1493

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

1495 # (INTERNAL) See C{radical2} below

1496 # assert d > EPS0

1497 r = fsum_(_1_0, (r1 / d)**2, -(r2 / d)**2) * _0_5

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

1499

1500

1501 def radical2(distance, radius1, radius2):

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

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

1504 Circle-CircleIntersection.html>}.

1505

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

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

1508

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

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

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

1512

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

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

1515

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

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

1518

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

1520 B{C{radius2}}.

1521

1522 @see: U{Circle-Circle Intersection

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

1524 '''

1525 d = Distance_(distance, low=_0_0)

1526 r1 = Radius_(radius1=radius1)

1527 r2 = Radius_(radius2=radius2)

1528 if d > (r1 + r2):

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

1530 txt=_too_(_distant_))

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

1532 Radical2Tuple(_0_5, _0_0)

1533

1534

1535 class Radical2Tuple(_NamedTuple):

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

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

1538 '''

1539 _Names_ = (_ratio_, _xline_)

1540 _Units_ = ( Scalar, Scalar)

1541

1542

1543 def _scale_deg(lat1, lat2): # degrees

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

1545 m = fabs(lat1 + lat2) * _0_5

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

1547

1548

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

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

1551 m = fabs(phi1 + phi2) * _0_5

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

1553

1554

1555 def _sincosa6(phi2, phi1, lam21):

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

1557 '''

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

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

1560

1561

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

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

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

1565 formula.

1566

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

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

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

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

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

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

1573 @kwarg wrap: Wrap and L{pygeodesy.unroll180} longitudes (C{bool}).

1574

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

1576 ellipsoid axes).

1577

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

1579

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

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

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

1583 '''

1584 return _distanceToE(thomas_, lat1, lat2, datum,

1585 *unroll180(lon1, lon2, wrap=wrap))

1586

1587

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

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

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

1591 formula.

1592

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

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

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

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

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

1598

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

1600

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

1602

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

1604 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

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

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

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

1608 Distance/ThomasFormula.php>}.

1609 '''

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

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

1612 E = _ellipsoidal(datum, thomas_)

1613 if E.f:

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

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

1616

1617 j = (r2 + r1) * _0_5

1618 k = (r2 - r1) * _0_5

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

1620

1621 h = fsum_(sk**2, (ck * h)**2, -(sj * h)**2)

1622 u = _1_0 - h

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

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

1625 sr, cr = sincos2(r)

1626 if isnon0(sr):

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

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

1629 x = u + h

1630 y = u - h

1631

1632 s = r / sr

1633 e = 4 * s**2

1634 d = 2 * cr

1635 a = e * d

1636 b = 2 * r

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

1638 f = E.f * _0_25

1639

1640 t = fsum_(a * x, -b * y, c * x**2, -d * y**2, e * x * y)

1641 r -= fsum_(s * x, -y, -t * f * _0_25) * f * sr

1642 return r

1643

1644

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

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

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

1648 spherical formula.

1649

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

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

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

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

1654 @kwarg radius: Mean earth radius, ellipsoid or datum (C{meter},

1655 L{Ellipsoid}, L{Ellipsoid2}, L{Datum} or L{a_f2Tuple}).

1656 @kwarg wrap: Wrap and L{pygeodesy.unroll180} longitudes (C{bool}).

1657

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

1659

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

1661

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

1663 L{cosineForsytheAndoyerLambert},L{cosineLaw}, L{equirectangular},

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

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

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

1667

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

1669 '''

1670 return _distanceToS(vincentys_, lat1, lat2, radius,

1671 *unroll180(lon1, lon2, wrap=wrap))

1672

1673

1674 def vincentys_(phi2, phi1, lam21):

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

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

1677 spherical formula.

1678

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

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

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

1682

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

1684

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

1686 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_},

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

1688 L{flatPolar_}, L{haversine_} and L{thomas_}.

1689

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

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

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

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

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

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

1696 '''

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

1698

1699 c = c2 * c21

1700 x = s1 * s2 + c1 * c

1701 y = c1 * s2 - s1 * c

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

1703

1704# **) MIT License

1705#

1706# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved.

1707#

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

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

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

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

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

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

1714#

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

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

1717#

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

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

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

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

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

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

1724# OTHER DEALINGS IN THE SOFTWARE.