Coverage for pygeodesy/formy.py: 98%

385 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-04-11 14:35 -0400

1 

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

3 

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

5''' 

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

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

8 

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

10from 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 

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

15 _mean_radius, _spherical_datum, _WGS84 

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

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

18 limiterrors, _ValueError, _xError 

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

20from pygeodesy.fsums import fsum_, isscalar, unstr 

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

22 _opposite_, _outside_, _too_ 

23from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS 

24from pygeodesy.named import _NamedTuple, _xnamed 

25from pygeodesy.namedTuples import Bearing2Tuple, Distance4Tuple, \ 

26 Intersection3Tuple, LatLon2Tuple, \ 

27 PhiLam2Tuple, Vector3Tuple 

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

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

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

31 Radius_, Scalar, _100km 

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

33 sincos2, sincos2_, sincos2d_, unroll180, unrollPI 

34 

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

36 

37__all__ = _ALL_LAZY.formy 

38__version__ = '23.04.11' 

39 

40_ratio_ = 'ratio' 

41_xline_ = 'xline' 

42 

43 

44def _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 

56def 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 

72def 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 

88def _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 

98def 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 

117def 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 

150def _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 

165def 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 

193def 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 

222def 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 

262def 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 

290def 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 

335def 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 

365def 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 

387def _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 

396def _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 

404def _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 

412def 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 

442def 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 

492def 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 

522def 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 

544def 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 

564def 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 

585def 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 

611def 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 

641def 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 

714def 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 

740def 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 

758def 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 

790hubeny = flatLocal # PYCHOK for Karl Hubeny 

791 

792 

793def 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 

822hubeny_ = flatLocal_ # PYCHOK for Karl Hubeny 

823 

824 

825def 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 

854def 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 

885def 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 

972def 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 

1002def 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 

1027def 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 

1061def 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 

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

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

1088 ''' 

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

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

1091 adjust=True, wrap=wrap) < _100km: 

1092 d, m = None, _MODS.vector3d 

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

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

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

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

1097 m = _MODS.sphericalNvector 

1098 _i = m.intersection 

1099 else: 

1100 d = _spherical_datum(datum, name=n) 

1101 if d.isSpherical: 

1102 m = _MODS.sphericalTrigonometry 

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

1104 elif d.isEllipsoidal: 

1105 try: 

1106 if d.ellipsoid.geodesic: 

1107 pass 

1108 m = _MODS.ellipsoidalKarney 

1109 except ImportError: 

1110 m = _MODS.ellipsoidalExact 

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

1112 else: 

1113 raise _AssertionError(datum=datum) 

1114 return _i, d, lon2, m, n 

1115 

1116 

1117def intersection2(lat1, lon1, bearing1, 

1118 lat2, lon2, bearing2, datum=None, wrap=True): 

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

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

1121 

1122 1) L{vector3d.intersection3d3} for small distances (below 100 KM or 

1123 about 0.9 degrees) or if no B{C{datum}} is specified, or ... 

1124 

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

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

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

1128 

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

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

1131 

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

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

1134 is installed, otherwise ... 

1135 

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

1137 

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

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

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

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

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

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

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

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

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

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

1148 

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

1150 longitude of the intersection point. 

1151 

1152 @raise IntersectionError: Ambiguous or infinite intersection 

1153 or colinear, parallel or otherwise 

1154 non-intersecting lines. 

1155 

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

1157 

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

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

1160 

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

1162 

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

1164 ''' 

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

1166 try: 

1167 _i, d, l2, m, n = _idlmn5(datum, lat1, lon1, lat2, lon2, wrap, False) 

1168 if d is None: 

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

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

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

1172 

1173 else: 

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

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

1176 if isinstance(t, Intersection3Tuple): # ellipsoidal 

1177 t, _, _ = t 

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

1179 

1180 except (TypeError, ValueError) as x: 

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

1182 lat2=lat2, lon2=lon2, bearing2=bearing2, 

1183 datum=datum, wrap=wrap) 

1184 return t 

1185 

1186 

1187def intersections2(lat1, lon1, radius1, 

1188 lat2, lon2, radius2, datum=None, wrap=True): 

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

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

1191 

1192 1) L{vector3d.intersections2} for small distances (below 100 KM or 

1193 about 0.9 degrees) or if no B{C{datum}} is specified, or ... 

1194 

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

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

1197 conventionally in C{meter} or ... 

1198 

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

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

1201 is installed, otherwise ... 

1202 

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

1204 

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

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

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

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

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

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

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

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

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

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

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

1216 

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

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

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

1220 

1221 @raise IntersectionError: Concentric, antipodal, invalid or 

1222 non-intersecting circles or no 

1223 convergence. 

1224 

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

1226 

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

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

1229 ''' 

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

1231 try: 

1232 _i, d, l2, m, n = _idlmn5(datum, lat1, lon1, lat2, lon2, wrap, True) 

1233 if d is None: 

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

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

1236 

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

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

1239 

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

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

1242 Vector=_V2T) 

1243 else: 

1244 

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

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

1247 

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

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

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

1251 

1252 except (TypeError, ValueError) as x: 

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

1254 lat2=lat2, lon2=lon2, radius2=radius2, 

1255 datum=datum, wrap=wrap) 

1256 return t 

1257 

1258 

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

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

1261 opposite sides of the earth. 

1262 

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

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

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

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

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

1268 

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

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

1271 

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

1273 ''' 

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

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

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

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

1278 

1279 

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

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

1282 opposite sides of the earth. 

1283 

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

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

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

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

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

1289 

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

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

1292 

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

1294 ''' 

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

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

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

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

1299 

1300 

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

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

1303 range in C{degrees}. 

1304 

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

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

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

1308 

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

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

1311 

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

1313 ''' 

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

1315 

1316 

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

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

1319 range in C{radians}. 

1320 

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

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

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

1324 

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

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

1327 

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

1329 ''' 

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

1331 

1332 

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

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

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

1336 

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

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

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

1340 

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

1342 

1343 @see: Function L{philam2n_xyz}. 

1344 

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

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

1347 ''' 

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

1349 

1350 

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

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

1353 ''' 

1354 if fabs(b) > n: 

1355 b = remainder(b, n2) 

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

1357 if r != a: 

1358 r = -r 

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

1360 return float0(r, b) 

1361 

1362 

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

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

1365 

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

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

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

1369 

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

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

1372 

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

1374 ''' 

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

1376 

1377 

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

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

1380 

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

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

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

1384 

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

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

1387 

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

1389 ''' 

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

1391 

1392 

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

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

1395 ''' 

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

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

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

1399 

1400 

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

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

1403 

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

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

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

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

1408 

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

1410 

1411 @see: Function L{n_xyz2philam}. 

1412 ''' 

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

1414 

1415 

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

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

1418 

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

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

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

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

1423 

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

1425 

1426 @see: Function L{n_xyz2latlon}. 

1427 ''' 

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

1429 

1430 

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

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

1433 ''' 

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

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

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

1437 

1438 

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

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

1441 

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

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

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

1445 

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

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

1448 

1449 @see: Function L{opposing_}. 

1450 ''' 

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

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

1453 

1454 

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

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

1457 

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

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

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

1461 

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

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

1464 

1465 @see: Function L{opposing}. 

1466 ''' 

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

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

1469 

1470 

1471def philam2n_xyz(phi, lam, name=NN): 

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

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

1474 

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

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

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

1478 

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

1480 

1481 @see: Function L{latlon2n_xyz}. 

1482 

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

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

1485 ''' 

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

1487 

1488 

1489def _radical2(d, r1, r2): # in .ellipsoidalBaseDI, .sphericalTrigonometry, .vector3d 

1490 # (INTERNAL) See C{radical2} below 

1491 # assert d > EPS0 

1492 r = fsum_(_1_0, (r1 / d)**2, -(r2 / d)**2) * _0_5 

1493 return Radical2Tuple(max(_0_0, min(_1_0, r)), r * d) 

1494 

1495 

1496def radical2(distance, radius1, radius2): 

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

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

1499 Circle-CircleIntersection.html>}. 

1500 

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

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

1503 

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

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

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

1507 

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

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

1510 

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

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

1513 

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

1515 B{C{radius2}}. 

1516 

1517 @see: U{Circle-Circle Intersection 

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

1519 ''' 

1520 d = Distance_(distance, low=_0_0) 

1521 r1 = Radius_(radius1=radius1) 

1522 r2 = Radius_(radius2=radius2) 

1523 if d > (r1 + r2): 

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

1525 txt=_too_(_distant_)) 

1526 return _radical2(d, r1, r2) if d > EPS0 else \ 

1527 Radical2Tuple(_0_5, _0_0) 

1528 

1529 

1530class Radical2Tuple(_NamedTuple): 

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

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

1533 ''' 

1534 _Names_ = (_ratio_, _xline_) 

1535 _Units_ = ( Scalar, Scalar) 

1536 

1537 

1538def _scale_deg(lat1, lat2): # degrees 

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

1540 m = fabs(lat1 + lat2) * _0_5 

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

1542 

1543 

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

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

1546 m = fabs(phi1 + phi2) * _0_5 

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

1548 

1549 

1550def _sincosa6(phi2, phi1, lam21): 

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

1552 ''' 

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

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

1555 

1556 

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

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

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

1560 formula. 

1561 

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

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

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

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

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

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

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

1569 

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

1571 ellipsoid axes). 

1572 

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

1574 

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

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

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

1578 ''' 

1579 return _distanceToE(thomas_, lat1, lat2, datum, 

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

1581 

1582 

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

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

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

1586 formula. 

1587 

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

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

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

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

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

1593 

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

1595 

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

1597 

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

1599 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_}, 

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

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

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

1603 Distance/ThomasFormula.php>}. 

1604 ''' 

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

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

1607 E = _ellipsoidal(datum, thomas_) 

1608 if E.f: 

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

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

1611 

1612 j = (r2 + r1) * _0_5 

1613 k = (r2 - r1) * _0_5 

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

1615 

1616 h = fsum_(sk**2, (ck * h)**2, -(sj * h)**2) 

1617 u = _1_0 - h 

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

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

1620 sr, cr = sincos2(r) 

1621 if isnon0(sr): 

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

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

1624 x = u + h 

1625 y = u - h 

1626 

1627 s = r / sr 

1628 e = 4 * s**2 

1629 d = 2 * cr 

1630 a = e * d 

1631 b = 2 * r 

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

1633 f = E.f * _0_25 

1634 

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

1636 r -= fsum_(s * x, -y, -t * f * _0_25) * f * sr 

1637 return r 

1638 

1639 

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

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

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

1643 spherical formula. 

1644 

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

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

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

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

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

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

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

1652 

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

1654 

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

1656 

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

1658 L{cosineForsytheAndoyerLambert},L{cosineLaw}, L{equirectangular}, 

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

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

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

1662 

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

1664 ''' 

1665 return _distanceToS(vincentys_, lat1, lat2, radius, 

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

1667 

1668 

1669def vincentys_(phi2, phi1, lam21): 

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

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

1672 spherical formula. 

1673 

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

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

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

1677 

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

1679 

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

1681 L{cosineForsytheAndoyerLambert_}, L{cosineLaw_}, 

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

1683 L{flatPolar_}, L{haversine_} and L{thomas_}. 

1684 

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

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

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

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

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

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

1691 ''' 

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

1693 

1694 c = c2 * c21 

1695 x = s1 * s2 + c1 * c 

1696 y = c1 * s2 - s1 * c 

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

1698 

1699# **) MIT License 

1700# 

1701# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved. 

1702# 

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

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

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

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

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

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

1709# 

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

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

1712# 

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

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

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

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

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

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

1719# OTHER DEALINGS IN THE SOFTWARE.