1

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

3

4 u'''A pure Python version of I{Karney}'s C++ class U{GeodesicExact

5<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>}.

6

7 Class L{GeodesicExact} follows the naming, methods and return values

8 of class C{Geodesic} from I{Karney}'s Python U{geographiclib

9<https://GitHub.com/geographiclib/geographiclib-python>}.

10

11 Copyright (C) U{Charles Karney<mailto:Charles@Karney.com>} (2008-2023)

12 and licensed under the MIT/X11 License. For more information, see the

13 U{GeographicLib<https://GeographicLib.SourceForge.io>} documentation.

14'''

15# make sure int/int division yields float quotient

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

17

18# A copy of comments from Karney's C{GeodesicExact.cpp}:

19#

20# This is a reformulation of the geodesic problem. The

21# notation is as follows:

22# - at a general point (no suffix or 1 or 2 as suffix)

23# - phi = latitude

24# - beta = latitude on auxiliary sphere

25# - omega = longitude on auxiliary sphere

26# - lambda = longitude

27# - alpha = azimuth of great circle

28# - sigma = arc length along great circle

29# - s = distance

30# - tau = scaled distance (= sigma at multiples of PI/2)

31# - at northwards equator crossing

32# - beta = phi = 0

33# - omega = lambda = 0

34# - alpha = alpha0

35# - sigma = s = 0

36# - a 12 suffix means a difference, e.g., s12 = s2 - s1.

37# - s and c prefixes mean sin and cos

38

39 from pygeodesy.basics import _xinstanceof, _xor, unsigned0

40 from pygeodesy.constants import EPS, EPS0, EPS02, MANT_DIG, NAN, PI, _EPSqrt, \

41 _SQRT2_2, isnan, _0_0, _0_001, _0_01, _0_1, _0_5, \

42 _1_0, _N_1_0, _1_75, _2_0, _N_2_0, _2__PI, _3_0, \

43 _4_0, _6_0, _8_0, _16_0, _90_0, _180_0, _1000_0

44# from pygeodesy.datums import _a_ellipsoid # from .karney

45# from pygeodesy.fmath import cbrt as _cbrt, hypot as hypot_ # from .karney

46 from pygeodesy.fsums import fsumf_, fsum1f_

47 from pygeodesy.geodesicx.gxbases import _cosSeries, _GeodesicBase, \

48 _sincos12, _sin1cos2, _xnC4

49 from pygeodesy.geodesicx.gxline import _GeodesicLineExact, _TINY, _update_glXs

50 from pygeodesy.interns import NN, _COMMASPACE_, _DOT_, _UNDER_

51 from pygeodesy.karney import _around, _atan2d, Caps, _cbrt, _copysign, _diff182, \

52 _EWGS84, _fix90, GDict, GeodesicError, _hypot, _K_2_0, \

53 _norm2, _norm180, _polynomial, _signBit, _sincos2, \

54 _sincos2d, _sincos2de, _unsigned2, _a_ellipsoid

55 from pygeodesy.lazily import _ALL_DOCS, _ALL_MODS as _MODS

56 from pygeodesy.namedTuples import Destination3Tuple, Distance3Tuple

57 from pygeodesy.props import deprecated_Property, Property, Property_RO

58 from pygeodesy.streprs import Fmt, pairs

59 from pygeodesy.utily import atan2d as _atan2d_reverse, _Wrap, wrap360

60

61 from math import atan2, copysign, cos, degrees, fabs, radians, sqrt

62

63__all__ = ()

64__version__ = '23.07.20'

65

66_MAXIT1 = 20

67_MAXIT2 = 10 + _MAXIT1 + MANT_DIG # MANT_DIG == C++ digits

68

69# increased multiplier in defn of _TOL1 from 100 to 200 to fix Inverse

70# case 52.784459512564 0 -52.784459512563990912 179.634407464943777557

71# which otherwise failed for Visual Studio 10 (Release and Debug)

72_TOL0 = EPS

73_TOL1 = _TOL0 * -200 # negative

74_TOL2 = _EPSqrt # == sqrt(_TOL0)

75_TOL3 = _TOL2 * _0_1

76_TOLb = _TOL2 * _TOL0 # Check on bisection interval

77_THR1 = _TOL2 * _1000_0 + _1_0

78

79_TINY3 = _TINY * _3_0

80_TOL08 = _TOL0 * _8_0

81_TOL016 = _TOL0 * _16_0

82

83

84 def _atan12(*sincos12, **sineg0):

85 '''(INTERNAL) Return C{ang12} in C{radians}.

86 '''

87 return atan2(*_sincos12(*sincos12, **sineg0))

88

89

90 def _eTOL2(f):

91 # Using the auxiliary sphere solution with dnm computed at

92 # (bet1 + bet2) / 2, the relative error in the azimuth

93 # consistency check is sig12^2 * abs(f) * min(1, 1-f/2) / 2.

94 # (Error measured for 1/100 < b/a < 100 and abs(f) >= 1/1000.

95

96 # For a given f and sig12, the max error occurs for lines

97 # near the pole. If the old rule for computing dnm = (dn1

98 # + dn2)/2 is used, then the error increases by a factor of

99 # 2.) Setting this equal to epsilon gives sig12 = etol2.

100

101 # Here 0.1 is a safety factor (error decreased by 100) and

102 # max(0.001, abs(f)) stops etol2 getting too large in the

103 # nearly spherical case.

104 t = min(_1_0, _1_0 - f * _0_5) * max(_0_001, fabs(f)) * _0_5

105 return _TOL3 / (sqrt(t) if t > EPS02 else EPS0)

106

107

108 class _PDict(GDict):

109 '''(INTERNAL) Parameters passed around in C{._GDictInverse} and

110 optionally returned when C{GeodesicExact.debug} is C{True}.

111 '''

112 def setsigs(self, ssig1, csig1, ssig2, csig2):

113 '''Update the C{sig1} and C{sig2} parameters.

114 '''

115 self.set_(ssig1=ssig1, csig1=csig1, sncndn1=(ssig1, csig1, self.dn1), # PYCHOK dn1

116 ssig2=ssig2, csig2=csig2, sncndn2=(ssig2, csig2, self.dn2)) # PYCHOK dn2

117

118 def toGDict(self): # PYCHOK no cover

119 '''Return as C{GDict} without attrs C{sncndn1} and C{sncndn2}.

120 '''

121 def _rest(sncndn1=None, sncndn2=None, **rest): # PYCHOK sncndn* not used

122 return GDict(rest)

123

124 return _rest(**self)

125

126

127 class GeodesicExact(_GeodesicBase):

128 '''A pure Python version of I{Karney}'s C++ class U{GeodesicExact

129 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>},

130 modeled after I{Karney}'s Python class U{geodesic.Geodesic<https://GitHub.com/

131 geographiclib/geographiclib-python>}.

132 '''

133 _E = _EWGS84

134 _nC4 = 30 # default C4order

135

136 def __init__(self, a_ellipsoid=_EWGS84, f=None, name=NN, C4order=None,

137 C4Order=None): # for backward compatibility

138 '''New L{GeodesicExact} instance.

139

140 @arg a_ellipsoid: An ellipsoid (L{Ellipsoid}) or datum (L{Datum}) or

141 the equatorial radius of the ellipsoid (C{scalar},

142 conventionally in C{meter}), see B{C{f}}.

143 @arg f: The flattening of the ellipsoid (C{scalar}) if B{C{a_ellipsoid}}

144 is specified as C{scalar}.

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

146 @kwarg C4order: Optional series expansion order (C{int}), see property

147 L{C4order}, default C{30}.

148 @kwarg C4Order: DEPRECATED, use keyword argument B{C{C4order}}.

149

150 @raise GeodesicError: Invalid B{C{C4order}}.

151 '''

152 if a_ellipsoid not in (GeodesicExact._E, None):

153 self._E = _a_ellipsoid(a_ellipsoid, f, name=name)

154

155 if name:

156 self.name = name

157 if C4order: # XXX private copy, always?

158 self.C4order = C4order

159 elif C4Order: # for backward compatibility

160 self.C4Order = C4Order

161

162 @Property_RO

163 def a(self):

164 '''Get the I{equatorial} radius, semi-axis (C{meter}).

165 '''

166 return self.ellipsoid.a

167

168 def ArcDirect(self, lat1, lon1, azi1, a12, outmask=Caps.STANDARD):

169 '''Solve the I{Direct} geodesic problem in terms of (spherical) arc length.

170

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

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

173 @arg azi1: Azimuth at the first point (compass C{degrees}).

174 @arg a12: Arc length between the points (C{degrees}), can be negative.

175 @kwarg outmask: Bit-or'ed combination of L{Caps} values specifying

176 the quantities to be returned.

177

178 @return: A L{GDict} with up to 12 items C{lat1, lon1, azi1, lat2,

179 lon2, azi2, m12, a12, s12, M12, M21, S12} with C{lat1},

180 C{lon1}, C{azi1} and arc length C{a12} always included.

181

182 @see: C++ U{GeodesicExact.ArcDirect

183 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>}

184 and Python U{Geodesic.ArcDirect<https://GeographicLib.SourceForge.io/Python/doc/code.html>}.

185 '''

186 return self._GDictDirect(lat1, lon1, azi1, True, a12, outmask)

187

188 def ArcDirectLine(self, lat1, lon1, azi1, a12, caps=Caps.ALL, name=NN):

189 '''Define a L{GeodesicLineExact} in terms of the I{direct} geodesic problem and as arc length.

190

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

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

193 @arg azi1: Azimuth at the first point (compass C{degrees}).

194 @arg a12: Arc length between the points (C{degrees}), can be negative.

195 @kwarg caps: Bit-or'ed combination of L{Caps} values specifying

196 the capabilities the L{GeodesicLineExact} instance

197 should possess, i.e., which quantities can be

198 returned by calls to L{GeodesicLineExact.Position}

199 and L{GeodesicLineExact.ArcPosition}.

200

201 @return: A L{GeodesicLineExact} instance.

202

203 @note: The third point of the L{GeodesicLineExact} is set to correspond

204 to the second point of the I{Inverse} geodesic problem.

205

206 @note: Latitude B{C{lat1}} should in the range C{[-90, +90]}.

207

208 @see: C++ U{GeodesicExact.ArcDirectLine

209 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>} and

210 Python U{Geodesic.ArcDirectLine<https://GeographicLib.SourceForge.io/Python/doc/code.html>}.

211 '''

212 return self._GenDirectLine(lat1, lon1, azi1, True, a12, caps, name=name)

213

214 def Area(self, polyline=False, name=NN):

215 '''Set up a L{GeodesicAreaExact} to compute area and

216 perimeter of a polygon.

217

218 @kwarg polyline: If C{True} perimeter only, otherwise

219 area and perimeter (C{bool}).

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

221

222 @return: A L{GeodesicAreaExact} instance.

223

224 @note: The B{C{debug}} setting is passed as C{verbose}

225 to the returned L{GeodesicAreaExact} instance.

226 '''

227 gaX = _MODS.geodesicx.GeodesicAreaExact(self, polyline=polyline,

228 name=name or self.name)

229 if self.debug:

230 gaX.verbose = True

231 return gaX

232

233 @Property_RO

234 def b(self):

235 '''Get the ellipsoid's I{polar} radius, semi-axis (C{meter}).

236 '''

237 return self.ellipsoid.b

238

239 @Property_RO

240 def c2x(self):

241 '''Get the ellipsoid's I{authalic} earth radius I{squared} (C{meter} I{squared}).

242 '''

243 # The Geodesic class substitutes atanh(sqrt(e2)) for asinh(sqrt(ep2))

244 # in the definition of _c2. The latter is more accurate for very

245 # oblate ellipsoids (which the Geodesic class does not handle). Of

246 # course, the area calculation in GeodesicExact is still based on a

247 # series and only holds for moderately oblate (or prolate) ellipsoids.

248 return self.ellipsoid.c2x

249

250 c2 = c2x # in this particular case

251

252 def C4f(self, eps):

253 '''Evaluate the C{C4x} coefficients for B{C{eps}}.

254

255 @arg eps: Polynomial factor (C{float}).

256

257 @return: C{C4order}-Tuple of C{C4x(B{eps})} coefficients.

258 '''

259 def _c4(nC4, C4x):

260 i, x, e = 0, _1_0, eps

261 _p = _polynomial

262 for r in range(nC4, 0, -1):

263 j = i + r

264 yield _p(e, C4x, i, j) * x

265 x *= e

266 i = j

267 # assert i == (nC4 * (nC4 + 1)) // 2

268

269 return tuple(_c4(self._nC4, self._C4x))

270

271 def _C4f_k2(self, k2): # in ._GDictInverse and gxline._GeodesicLineExact._C4a

272 '''(INTERNAL) Compute C{eps} from B{C{k2}} and invoke C{C4f}.

273 '''

274 return self.C4f(k2 / fsumf_(_2_0, sqrt(k2 + _1_0) * _2_0, k2))

275

276 @Property

277 def C4order(self):

278 '''Get the series expansion order (C{int}, 24, 27 or 30).

279 '''

280 return self._nC4

281

282 @C4order.setter # PYCHOK .setter!

283 def C4order(self, order):

284 '''Set the series expansion order (C{int}, 24, 27 or 30).

285

286 @raise GeodesicError: Invalid B{C{order}}.

287 '''

288 _xnC4(C4order=order)

289 if self._nC4 != order:

290 GeodesicExact._C4x._update(self)

291 _update_glXs(self) # zap cached _GeodesicLineExact attrs _B41, _C4a

292 self._nC4 = order

293

294 @deprecated_Property

295 def C4Order(self):

296 '''DEPRECATED, use property C{C4order}.

297 '''

298 return self.C4order

299

300 @C4Order.setter # PYCHOK .setter!

301 def C4Order(self, order):

302 '''DEPRECATED, use property C{C4order}.

303 '''

304 _xnC4(C4Order=order)

305 self.C4order = order

306

307 @Property_RO

308 def _C4x(self):

309 '''Get this ellipsoid's C{C4} coefficients, I{cached} tuple.

310

311 @see: Property L{C4order}.

312 '''

313 # see C4coeff() in GeographicLib.src.GeodesicExactC4.cpp

314 def _C4(nC4):

315 i, n, cs = 0, self.n, _C4coeffs(nC4)

316 _p = _polynomial

317 for r in range(nC4 + 1, 1, -1):

318 for j in range(1, r):

319 j = j + i # (j - i - 1) order of polynomial

320 yield _p(n, cs, i, j) / cs[j]

321 i = j + 1

322 # assert i == (nC4 * (nC4 + 1) * (nC4 + 5)) // 6

323

324 return tuple(_C4(self._nC4)) # 3rd flattening

325

326 def Direct(self, lat1, lon1, azi1, s12, outmask=Caps.STANDARD):

327 '''Solve the I{Direct} geodesic problem

328

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

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

331 @arg azi1: Azimuth at the first point (compass C{degrees}).

332 @arg s12: Distance between the points (C{meter}), can be negative.

333 @kwarg outmask: Bit-or'ed combination of L{Caps} values specifying

334 the quantities to be returned.

335

336 @return: A L{GDict} with up to 12 items C{lat1, lon1, azi1, lat2,

337 lon2, azi2, m12, a12, s12, M12, M21, S12} with C{lat1},

338 C{lon1}, C{azi1} and distance C{s12} always included.

339

340 @see: C++ U{GeodesicExact.Direct

341 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>}

342 and Python U{Geodesic.Direct<https://GeographicLib.SourceForge.io/Python/doc/code.html>}.

343 '''

344 return self._GDictDirect(lat1, lon1, azi1, False, s12, outmask)

345

346 def Direct3(self, lat1, lon1, azi1, s12): # PYCHOK outmask

347 '''Return the destination lat, lon and reverse azimuth

348 (final bearing) in C{degrees}.

349

350 @return: L{Destination3Tuple}C{(lat, lon, final)}.

351 '''

352 r = self._GDictDirect(lat1, lon1, azi1, False, s12, Caps._AZIMUTH_LATITUDE_LONGITUDE)

353 return Destination3Tuple(r.lat2, r.lon2, r.azi2) # no iteration

354

355 def DirectLine(self, lat1, lon1, azi1, s12, caps=Caps.STANDARD, name=NN):

356 '''Define a L{GeodesicLineExact} in terms of the I{direct} geodesic problem and as distance.

357

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

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

360 @arg azi1: Azimuth at the first point (compass C{degrees}).

361 @arg s12: Distance between the points (C{meter}), can be negative.

362 @kwarg caps: Bit-or'ed combination of L{Caps} values specifying

363 the capabilities the L{GeodesicLineExact} instance

364 should possess, i.e., which quantities can be

365 returned by calls to L{GeodesicLineExact.Position}.

366

367 @return: A L{GeodesicLineExact} instance.

368

369 @note: The third point of the L{GeodesicLineExact} is set to correspond

370 to the second point of the I{Inverse} geodesic problem.

371

372 @note: Latitude B{C{lat1}} should in the range C{[-90, +90]}.

373

374 @see: C++ U{GeodesicExact.DirectLine

375 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>} and

376 Python U{Geodesic.DirectLine<https://GeographicLib.SourceForge.io/Python/doc/code.html>}.

377 '''

378 return self._GenDirectLine(lat1, lon1, azi1, False, s12, caps, name=name)

379

380 def _dn(self, sbet, cbet): # in gxline._GeodesicLineExact.__init__

381 '''(INTERNAL) Helper.

382 '''

383 if self.f < 0: # PYCHOK no cover

384 dn = sqrt(_1_0 - cbet**2 * self.e2) / self.f1

385 else:

386 dn = sqrt(_1_0 + sbet**2 * self.ep2)

387 return dn

388

389 @Property_RO

390 def e2(self):

391 '''Get the ellipsoid's I{(1st) eccentricity squared} (C{float}), M{f * (2 - f)}.

392 '''

393 return self.ellipsoid.e2

394

395 @Property_RO

396 def _e2a2(self):

397 '''(INTERNAL) Cache M{E.e2 * E.a2}.

398 '''

399 return self.e2 * self.ellipsoid.a2

400

401 @Property_RO

402 def _e2_f1(self):

403 '''(INTERNAL) Cache M{E.e2 * E.f1}.

404 '''

405 return self.e2 / self.f1

406

407 @Property_RO

408 def _eF(self):

409 '''(INTERNAL) Get the elliptic function, aka C{.E}.

410 '''

411 return _MODS.elliptic.Elliptic(k2=-self.ep2)

412

413 def _eF_reset_cHe2_f1(self, x, y):

414 '''(INTERNAL) Reset elliptic function and return M{cH * e2 / f1 * ...}.

415 '''

416 self._eF_reset_k2(x)

417 return y * self._eF.cH * self._e2_f1

418

419 def _eF_reset_k2(self, x):

420 '''(INTERNAL) Reset elliptic function and return C{k2}.

421 '''

422 ep2 = self.ep2

423 k2 = x**2 * ep2 # see .gxline._GeodesicLineExact._eF

424 self._eF.reset(k2=-k2, alpha2=-ep2) # kp2, alphap2 defaults

425 _update_glXs(self) # zap cached/memoized _GeodesicLineExact attrs

426 return k2

427

428 @Property_RO

429 def ellipsoid(self):

430 '''Get the ellipsoid (C{Ellipsoid}).

431 '''

432 return self._E

433

434 @Property_RO

435 def ep2(self):

436 '''Get the ellipsoid's I{2nd eccentricity squared} (C{float}), M{e2 / (1 - e2)}.

437 '''

438 return self.ellipsoid.e22 # == self.e2 / self.f1**2

439

440 e22 = ep2 # for ellipsoid compatibility

441

442 @Property_RO

443 def _eTOL2(self):

444 '''(INTERNAL) The si12 threshold for "really short".

445 '''

446 return _eTOL2(self.f)

447

448 @Property_RO

449 def f(self):

450 '''Get the ellipsoid's I{flattening} (C{float}), M{(a - b) / a}, C{0} for spherical, negative for prolate.

451 '''

452 return self.ellipsoid.f

453

454 flattening = f

455

456 @Property_RO

457 def f1(self): # in .css.CassiniSoldner.reset

458 '''Get the ellipsoid's I{1 - flattening} (C{float}).

459 '''

460 return self.ellipsoid.f1

461

462 @Property_RO

463 def _f180(self):

464 '''(INTERNAL) Cached/memoized.

465 '''

466 return self.f * _180_0

467

468 def _GDictDirect(self, lat1, lon1, azi1, arcmode, s12_a12, outmask=Caps.STANDARD):

469 '''(INTERNAL) As C{_GenDirect}, but returning a L{GDict}.

470

471 @return: A L{GDict} ...

472 '''

473 C = outmask if arcmode else (outmask | Caps.DISTANCE_IN)

474 glX = self.Line(lat1, lon1, azi1, C | Caps.LINE_OFF)

475 return glX._GDictPosition(arcmode, s12_a12, outmask)

476

477 def _GDictInverse(self, lat1, lon1, lat2, lon2, outmask=Caps.STANDARD): # MCCABE 33, 41 vars

478 '''(INTERNAL) As C{_GenInverse}, but returning a L{GDict}.

479

480 @return: A L{GDict} ...

481 '''

482 Cs = Caps

483 if self._debug: # PYCHOK no cover

484 outmask |= Cs._DEBUG_INVERSE & self._debug

485 outmask &= Cs._OUT_MASK # incl. _SALPs_CALPs and _DEBUG_

486 # compute longitude difference carefully (with _diff182):

487 # result is in [-180, +180] but -180 is only for west-going

488 # geodesics, +180 is for east-going and meridional geodesics

489 lon12, lon12s = _diff182(lon1, lon2)

490 # see C{result} from geographiclib.geodesic.Inverse

491 if (outmask & Cs.LONG_UNROLL): # == (lon1 + lon12) + lon12s

492 r = GDict(lon1=lon1, lon2=fsumf_(lon1, lon12, lon12s))

493 else:

494 r = GDict(lon1=_norm180(lon1), lon2=_norm180(lon2))

495 if _K_2_0: # GeographicLib 2.0

496 # make longitude difference positive

497 lon12, lon_ = _unsigned2(lon12)

498 if lon_:

499 lon12s = -lon12s

500 lam12 = radians(lon12)

501 # calculate sincosd(_around(lon12 + correction))

502 slam12, clam12 = _sincos2de(lon12, lon12s)

503 # supplementary longitude difference

504 lon12s = fsumf_(_180_0, -lon12, -lon12s)

505 else: # GeographicLib 1.52

506 # make longitude difference positive and if very close

507 # to being on the same half-meridian, then make it so.

508 if lon12 < 0: # _signBit(lon12)

509 lon_, lon12 = True, -_around(lon12)

510 lon12s = _around(fsumf_(_180_0, -lon12, lon12s))

511 else:

512 lon_, lon12 = False, _around(lon12)

513 lon12s = _around(fsumf_(_180_0, -lon12, -lon12s))

514 lam12 = radians(lon12)

515 if lon12 > _90_0:

516 slam12, clam12 = _sincos2d(lon12s)

517 clam12 = -clam12

518 else:

519 slam12, clam12 = _sincos2(lam12)

520 # If really close to the equator, treat as on equator.

521 lat1 = _around(_fix90(lat1))

522 lat2 = _around(_fix90(lat2))

523 r.set_(lat1=lat1, lat2=lat2)

524 # Swap points so that point with higher (abs) latitude is

525 # point 1. If one latitude is a NAN, then it becomes lat1.

526 swap_ = fabs(lat1) < fabs(lat2) or isnan(lat2)

527 if swap_:

528 lat1, lat2 = lat2, lat1

529 lon_ = not lon_

530 if _signBit(lat1):

531 lat_ = False # note, False

532 else: # make lat1 <= -0

533 lat_ = True # note, True

534 lat1, lat2 = -lat1, -lat2

535 # Now 0 <= lon12 <= 180, -90 <= lat1 <= -0 and lat1 <= lat2 <= -lat1

536 # and lat_, lon_, swap_ register the transformation to bring the

537 # coordinates to this canonical form, where False means no change

538 # made. We make these transformations so that there are few cases

539 # to check, e.g., on verifying quadrants in atan2. In addition,

540 # this enforces some symmetries in the results returned.

541

542 # Initialize for the meridian. No longitude calculation is

543 # done in this case to let the parameter default to 0.

544 sbet1, cbet1 = self._sinf1cos2d(lat1)

545 sbet2, cbet2 = self._sinf1cos2d(lat2)

546 # If cbet1 < -sbet1, then cbet2 - cbet1 is a sensitive measure

547 # of the |bet1| - |bet2|. Alternatively (cbet1 >= -sbet1),

548 # abs(sbet2) + sbet1 is a better measure. This logic is used

549 # in assigning calp2 in _Lambda6. Sometimes these quantities

550 # vanish and in that case we force bet2 = +/- bet1 exactly. An

551 # example where is is necessary is the inverse problem

552 # 48.522876735459 0 -48.52287673545898293 179.599720456223079643

553 # which failed with Visual Studio 10 (Release and Debug)

554 if cbet1 < -sbet1:

555 if cbet2 == cbet1:

556 sbet2 = copysign(sbet1, sbet2)

557 elif fabs(sbet2) == -sbet1:

558 cbet2 = cbet1

559

560 p = _PDict(sbet1=sbet1, cbet1=cbet1, dn1=self._dn(sbet1, cbet1),

561 sbet2=sbet2, cbet2=cbet2, dn2=self._dn(sbet2, cbet2))

562

563 _meridian = _b = True # i.e. not meridian, not b

564 if lat1 == -90 or slam12 == 0:

565 # Endpoints are on a single full meridian,

566 # so the geodesic might lie on a meridian.

567 salp1, calp1 = slam12, clam12 # head to target lon

568 salp2, calp2 = _0_0, _1_0 # then head north

569 # tan(bet) = tan(sig) * cos(alp)

570 p.setsigs(sbet1, calp1 * cbet1, sbet2, calp2 * cbet2)

571 # sig12 = sig2 - sig1

572 sig12 = _atan12(sbet1, p.csig1, sbet2, p.csig2, sineg0=True) # PYCHOK csig*

573 s12x, m12x, _, \

574 M12, M21 = self._Length5(sig12, outmask | Cs.REDUCEDLENGTH, p)

575 # Add the check for sig12 since zero length geodesics

576 # might yield m12 < 0. Test case was

577 # echo 20.001 0 20.001 0 | GeodSolve -i

578 # In fact, we will have sig12 > PI/2 for meridional

579 # geodesic which is not a shortest path.

580 if m12x >= 0 or sig12 < _1_0:

581 # Need at least 2 to handle 90 0 90 180

582 # Prevent negative s12 or m12 from geographiclib 1.52

583 if sig12 < _TINY3 or (sig12 < _TOL0 and (s12x < 0 or m12x < 0)):

584 sig12 = m12x = s12x = _0_0

585 else:

586 _b = False # apply .b to s12x, m12x

587 _meridian = False

588 C = 1

589 # else: # m12 < 0, prolate and too close to anti-podal

590 # _meridian = True

591 a12 = _0_0 # if _b else degrees(sig12)

592

593 if _meridian:

594 _b = sbet1 == 0 and (self.f <= 0 or lon12s >= self._f180) # and sbet2 == 0

595 if _b: # Geodesic runs along equator

596 calp1 = calp2 = _0_0

597 salp1 = salp2 = _1_0

598 sig12 = lam12 / self.f1 # == omg12

599 somg12, comg12 = _sincos2(sig12)

600 m12x = self.b * somg12

601 s12x = self.a * lam12

602 M12 = M21 = comg12

603 a12 = lon12 / self.f1

604 C = 2

605 else:

606 # Now point1 and point2 belong within a hemisphere bounded by a

607 # meridian and geodesic is neither meridional or equatorial.

608 p.set_(slam12=slam12, clam12=clam12)

609 # Figure a starting point for Newton's method

610 sig12, salp1, calp1, \

611 salp2, calp2, dnm = self._InverseStart6(lam12, p)

612 if sig12 is None: # use Newton's method

613 # pre-compute the constant _Lambda6 term, once

614 p.set_(bet12=None if cbet2 == cbet1 and fabs(sbet2) == -sbet1 else

615 (((cbet1 + cbet2) * (cbet2 - cbet1)) if cbet1 < -sbet1 else

616 ((sbet1 + sbet2) * (sbet1 - sbet2))))

617 sig12, salp1, calp1, \

618 salp2, calp2, domg12 = self._Newton6(salp1, calp1, p)

619 s12x, m12x, _, M12, M21 = self._Length5(sig12, outmask, p)

620 if (outmask & Cs.AREA):

621 # omg12 = lam12 - domg12

622 s, c = _sincos2(domg12)

623 somg12, comg12 = _sincos12(s, c, slam12, clam12)

624 C = 3 # Newton

625 else: # from _InverseStart6: dnm, salp*, calp*

626 C = 4 # Short lines

627 s, c = _sincos2(sig12 / dnm)

628 m12x = dnm**2 * s

629 s12x = dnm * sig12

630 M12 = M21 = c

631 if (outmask & Cs.AREA):

632 somg12, comg12 = _sincos2(lam12 / (self.f1 * dnm))

633

634 else: # _meridian is False

635 somg12 = comg12 = NAN

636

637 r.set_(a12=a12 if _b else degrees(sig12)) # in [0, 180]

638

639 if (outmask & Cs.DISTANCE):

640 r.set_(s12=unsigned0(s12x if _b else (self.b * s12x)))

641

642 if (outmask & Cs.REDUCEDLENGTH):

643 r.set_(m12=unsigned0(m12x if _b else (self.b * m12x)))

644

645 if (outmask & Cs.GEODESICSCALE):

646 if swap_:

647 M12, M21 = M21, M12

648 r.set_(M12=unsigned0(M12),

649 M21=unsigned0(M21))

650

651 if (outmask & Cs.AREA):

652 S12 = self._InverseArea(_meridian, salp1, calp1,

653 salp2, calp2,

654 somg12, comg12, p)

655 if _xor(swap_, lat_, lon_):

656 S12 = -S12

657 r.set_(S12=unsigned0(S12))

658

659 if (outmask & (Cs.AZIMUTH | Cs._SALPs_CALPs)):

660 if swap_:

661 salp1, salp2 = salp2, salp1

662 calp1, calp2 = calp2, calp1

663 if _xor(swap_, lon_):

664 salp1, salp2 = -salp1, -salp2

665 if _xor(swap_, lat_):

666 calp1, calp2 = -calp1, -calp2

667

668 if (outmask & Cs.AZIMUTH):

669 r.set_(azi1=_atan2d(salp1, calp1),

670 azi2=_atan2d_reverse(salp2, calp2, reverse=outmask & Cs.REVERSE2))

671 if (outmask & Cs._SALPs_CALPs):

672 r.set_(salp1=salp1, calp1=calp1,

673 salp2=salp2, calp2=calp2)

674

675 if (outmask & Cs._DEBUG_INVERSE): # PYCHOK no cover

676 E, eF = self.ellipsoid, self._eF

677 p.set_(C=C, a=self.a, f=self.f, f1=self.f1,

678 e=E.e, e2=self.e2, ep2=self.ep2,

679 c2=E.c2, c2x=self.c2x,

680 eFcD=eF.cD, eFcE=eF.cE, eFcH=eF.cH,

681 eFk2=eF.k2, eFa2=eF.alpha2)

682 p.update(r) # r overrides p

683 r = p.toGDict()

684 return self._iter2tion(r, p)

685

686 def _GenDirect(self, lat1, lon1, azi1, arcmode, s12_a12, outmask=Caps.STANDARD):

687 '''(INTERNAL) The general I{Inverse} geodesic calculation.

688

689 @return: L{Direct9Tuple}C{(a12, lat2, lon2, azi2,

690 s12, m12, M12, M21, S12)}.

691 '''

692 r = self._GDictDirect(lat1, lon1, azi1, arcmode, s12_a12, outmask)

693 return r.toDirect9Tuple()

694

695 def _GenDirectLine(self, lat1, lon1, azi1, arcmode, s12_a12, caps, name=NN):

696 '''(INTERNAL) Helper for C{ArcDirectLine} and C{DirectLine}.

697

698 @return: A L{GeodesicLineExact} instance.

699 '''

700 azi1 = _norm180(azi1)

701 # guard against underflow in salp0. Also -0 is converted to +0.

702 s, c = _sincos2d(_around(azi1))

703 C = caps if arcmode else (caps | Caps.DISTANCE_IN)

704 return _GeodesicLineExact(self, lat1, lon1, azi1, C,

705 self._debug, s, c, name=name)._GenSet(arcmode, s12_a12)

706

707 def _GenInverse(self, lat1, lon1, lat2, lon2, outmask=Caps.STANDARD):

708 '''(INTERNAL) The general I{Inverse} geodesic calculation.

709

710 @return: L{Inverse10Tuple}C{(a12, s12, salp1, calp1, salp2, calp2,

711 m12, M12, M21, S12)}.

712 '''

713 r = self._GDictInverse(lat1, lon1, lat2, lon2, outmask | Caps._SALPs_CALPs)

714 return r.toInverse10Tuple()

715

716 def Inverse(self, lat1, lon1, lat2, lon2, outmask=Caps.STANDARD):

717 '''Perform the I{Inverse} geodesic calculation.

718

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

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

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

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

723 @kwarg outmask: Bit-or'ed combination of L{Caps} values specifying

724 the quantities to be returned.

725

726 @return: A L{GDict} with up to 12 items C{lat1, lon1, azi1, lat2,

727 lon2, azi2, m12, a12, s12, M12, M21, S12} with C{lat1},

728 C{lon1}, C{azi1} and distance C{s12} always included.

729

730 @note: The third point of the L{GeodesicLineExact} is set to correspond

731 to the second point of the I{Inverse} geodesic problem.

732

733 @note: Both B{C{lat1}} and B{C{lat2}} should in the range C{[-90, +90]}.

734

735 @see: C++ U{GeodesicExact.InverseLine

736 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>} and

737 Python U{Geodesic.InverseLine<https://GeographicLib.SourceForge.io/Python/doc/code.html>}.

738 '''

739 return self._GDictInverse(lat1, lon1, lat2, lon2, outmask)

740

741 def Inverse1(self, lat1, lon1, lat2, lon2, wrap=False):

742 '''Return the non-negative, I{angular} distance in C{degrees}.

743

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

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

746 '''

747 # see .FrechetKarney.distance, .HausdorffKarney._distance

748 # and .HeightIDWkarney._distances

749 if wrap:

750 _, lat2, lon2 = _Wrap.latlon3(lat1, lat2, lon2, True) # _Geodesic.LONG_UNROLL

751 return fabs(self._GDictInverse(lat1, lon1, lat2, lon2, Caps._ANGLE_ONLY).a12)

752

753 def Inverse3(self, lat1, lon1, lat2, lon2): # PYCHOK outmask

754 '''Return the distance in C{meter} and the forward and

755 reverse azimuths (initial and final bearing) in C{degrees}.

756

757 @return: L{Distance3Tuple}C{(distance, initial, final)}.

758 '''

759 r = self._GDictInverse(lat1, lon1, lat2, lon2, Caps.AZIMUTH_DISTANCE)

760 return Distance3Tuple(r.s12, wrap360(r.azi1), wrap360(r.azi2),

761 iteration=r.iteration)

762

763 def InverseLine(self, lat1, lon1, lat2, lon2, caps=Caps.STANDARD, name=NN):

764 '''Define a L{GeodesicLineExact} in terms of the I{Inverse} geodesic problem.

765

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

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

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

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

770 @kwarg caps: Bit-or'ed combination of L{Caps} values specifying

771 the capabilities the L{GeodesicLineExact} instance

772 should possess, i.e., which quantities can be

773 returned by calls to L{GeodesicLineExact.Position}

774 and L{GeodesicLineExact.ArcPosition}.

775

776 @return: A L{GeodesicLineExact} instance.

777

778 @note: The third point of the L{GeodesicLineExact} is set to correspond

779 to the second point of the I{Inverse} geodesic problem.

780

781 @note: Both B{C{lat1}} and B{C{lat2}} should in the range C{[-90, +90]}.

782

783 @see: C++ U{GeodesicExact.InverseLine

784 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>} and

785 Python U{Geodesic.InverseLine<https://GeographicLib.SourceForge.io/Python/doc/code.html>}.

786 '''

787 Cs = Caps

788 r = self._GDictInverse(lat1, lon1, lat2, lon2, Cs._SALPs_CALPs) # No need for AZIMUTH

789 C = (caps | Cs.DISTANCE) if (caps & Cs._DISTANCE_IN_OUT) else caps

790 azi1 = _atan2d(r.salp1, r.calp1)

791 return _GeodesicLineExact(self, lat1, lon1, azi1, C, # ensure a12 is distance

792 self._debug, r.salp1, r.calp1, name=name)._GenSet(True, r.a12)

793

794 def _InverseArea(self, _meridian, salp1, calp1, # PYCHOK 9 args

795 salp2, calp2,

796 somg12, comg12, p):

797 '''(INTERNAL) Split off from C{_GDictInverse} to reduce complexity/length.

798

799 @return: Area C{S12}.

800 '''

801 # from _Lambda6: sin(alp1) * cos(bet1) = sin(alp0), calp0 > 0

802 salp0, calp0 = _sin1cos2(salp1, calp1, p.sbet1, p.cbet1)

803 A4 = calp0 * salp0

804 if A4:

805 # from _Lambda6: tan(bet) = tan(sig) * cos(alp)

806 k2 = calp0**2 * self.ep2

807 C4a = self._C4f_k2(k2)

808 B41 = _cosSeries(C4a, *_norm2(p.sbet1, calp1 * p.cbet1))

809 B42 = _cosSeries(C4a, *_norm2(p.sbet2, calp2 * p.cbet2))

810 # multiplier = a^2 * e^2 * cos(alpha0) * sin(alpha0)

811 A4 *= self._e2a2

812 S12 = A4 * (B42 - B41)

813 else: # avoid problems with indeterminate sig1, sig2 on equator

814 A4 = B41 = B42 = k2 = S12 = _0_0

815

816 if (_meridian and # omg12 < 3/4 * PI

817 comg12 > -_SQRT2_2 and # lon diff not too big

818 (p.sbet2 - p.sbet1) < _1_75): # lat diff not too big

819 # use tan(Gamma/2) = tan(omg12/2) *

820 # (tan(bet1/2) + tan(bet2/2)) /

821 # (tan(bet1/2) * tan(bet2/2) + 1))

822 # with tan(x/2) = sin(x) / (1 + cos(x))

823 dbet1 = p.cbet1 + _1_0

824 dbet2 = p.cbet2 + _1_0

825 domg12 = comg12 + _1_0

826 salp12 = (p.sbet1 * dbet2 + dbet1 * p.sbet2) * somg12

827 calp12 = (p.sbet1 * p.sbet2 + dbet1 * dbet2) * domg12

828 alp12 = _2_0 * atan2(salp12, calp12)

829 else:

830 # alp12 = alp2 - alp1, used in atan2, no need to normalize

831 salp12, calp12 = _sincos12(salp1, calp1, salp2, calp2)

832 # The right thing appears to happen if alp1 = +/-180 and

833 # alp2 = 0, viz salp12 = -0 and alp12 = -180. However,

834 # this depends on the sign being attached to 0 correctly.

835 # Following ensures the correct behavior.

836 if salp12 == 0 and calp12 < 0:

837 alp12 = _copysign(PI, calp1)

838 else:

839 alp12 = atan2(salp12, calp12)

840

841 p.set_(alp12=alp12, A4=A4, B41=B41, B42=B42, k2=k2)

842 return S12 + self.c2x * alp12

843

844 def _InverseStart6(self, lam12, p):

845 '''(INTERNAL) Return a starting point for Newton's method in

846 C{salp1} and C{calp1} indicated by C{sig12=None}. If

847 Newton's method doesn't need to be used, return also

848 C{salp2}, C{calp2}, C{dnm} and C{sig12} non-C{None}.

849

850 @return: 6-Tuple C{(sig12, salp1, calp1, salp2, calp2, dnm)}

851 and C{p.setsigs} updated for Newton, C{sig12=None}.

852 '''

853 sig12 = None # use Newton

854 salp1 = calp1 = salp2 = calp2 = dnm = NAN

855

856 # bet12 = bet2 - bet1 in [0, PI)

857 sbet12, cbet12 = _sincos12(p.sbet1, p.cbet1, p.sbet2, p.cbet2)

858 shortline = cbet12 >= 0 and sbet12 < _0_5 and (p.cbet2 * lam12) < _0_5

859 if shortline:

860 # sin((bet1 + bet2)/2)^2 = (sbet1 + sbet2)^2 / (

861 # (cbet1 + cbet2)^2 + (sbet1 + sbet2)^2)

862 t = (p.sbet1 + p.sbet2)**2

863 s = t / ((p.cbet1 + p.cbet2)**2 + t)

864 dnm = sqrt(_1_0 + self.ep2 * s)

865 somg12, comg12 = _sincos2(lam12 / (self.f1 * dnm))

866 else:

867 somg12, comg12 = p.slam12, p.clam12

868

869 # bet12a = bet2 + bet1 in (-PI, 0], note -sbet1

870 sbet12a, cbet12a = _sincos12(-p.sbet1, p.cbet1, p.sbet2, p.cbet2)

871

872 c = fabs(comg12) + _1_0 # == (1 - comg12) if comg12 < 0

873 s = somg12**2 / c

874 t = p.sbet1 * p.cbet2 * s

875 salp1 = p.cbet2 * somg12

876 calp1 = (sbet12a - t) if comg12 < 0 else (sbet12 + t)

877

878 ssig12 = _hypot(salp1, calp1)

879 csig12 = p.sbet1 * p.sbet2 + p.cbet1 * p.cbet2 * comg12

880

881 if shortline and ssig12 < self._eTOL2: # really short lines

882 t = c if comg12 < 0 else s

883 salp2, calp2 = _norm2(somg12 * p.cbet1,

884 sbet12 - p.cbet1 * p.sbet2 * t)

885 sig12 = atan2(ssig12, csig12) # do not use Newton

886

887 elif (self._n_0_1 or # Skip astroid calc if too eccentric

888 csig12 >= 0 or ssig12 >= (p.cbet1**2 * self._n6PI)):

889 pass # nothing to do, 0th order spherical approximation OK

890

891 else:

892 # Scale lam12 and bet2 to x, y coordinate system where antipodal

893 # point is at origin and singular point is at y = 0, x = -1

894 lam12x = atan2(-p.slam12, -p.clam12) # lam12 - PI

895 f = self.f

896 if f < 0: # PYCHOK no cover

897 # ssig1=sbet1, csig1=-cbet1, ssig2=sbet2, csig2=cbet2

898 p.setsigs(p.sbet1, -p.cbet1, p.sbet2, p.cbet2)

899 # if lon12 = 180, this repeats a calculation made in Inverse

900 _, m12b, m0, _, _ = self._Length5(atan2(sbet12a, cbet12a) + PI,

901 Caps.REDUCEDLENGTH, p)

902 t = p.cbet1 * PI # x = dlat, y = dlon

903 x = m12b / (t * p.cbet2 * m0) - _1_0

904 sca = (sbet12a / (x * p.cbet1)) if x < -_0_01 else (-f * t)

905 y = lam12x / sca

906 else: # f >= 0, however f == 0 does not get here

907 sca = self._eF_reset_cHe2_f1(p.sbet1, p.cbet1 * _2_0)

908 x = lam12x / sca # dlon

909 y = sbet12a / (sca * p.cbet1) # dlat

910

911 if y > _TOL1 and x > -_THR1: # strip near cut

912 if f < 0: # PYCHOK no cover

913 calp1 = max( _0_0, x) if x > _TOL1 else max(_N_1_0, x)

914 salp1 = sqrt(_1_0 - calp1**2)

915 else:

916 salp1 = min( _1_0, -x)

917 calp1 = -sqrt(_1_0 - salp1**2)

918 else:

919 # Estimate alp1, by solving the astroid problem.

920 #

921 # Could estimate alpha1 = theta + PI/2, directly, i.e.,

922 # calp1 = y/k; salp1 = -x/(1+k); for _f >= 0

923 # calp1 = x/(1+k); salp1 = -y/k; for _f < 0 (need to check)

924 #

925 # However, it's better to estimate omg12 from astroid and use

926 # spherical formula to compute alp1. This reduces the mean

927 # number of Newton iterations for astroid cases from 2.24

928 # (min 0, max 6) to 2.12 (min 0, max 5). The changes in the

929 # number of iterations are as follows:

930 #

931 # change percent

932 # 1 5

933 # 0 78

934 # -1 16

935 # -2 0.6

936 # -3 0.04

937 # -4 0.002

938 #

939 # The histogram of iterations is (m = number of iterations

940 # estimating alp1 directly, n = number of iterations

941 # estimating via omg12, total number of trials = 148605):

942 #

943 # iter m n

944 # 0 148 186

945 # 1 13046 13845

946 # 2 93315 102225

947 # 3 36189 32341

948 # 4 5396 7

949 # 5 455 1

950 # 6 56 0

951 #

952 # omg12 is near PI, estimate work with omg12a = PI - omg12

953 k = _Astroid(x, y)

954 sca *= (y * (k + _1_0) / k) if f < 0 else \

955 (x * k / (k + _1_0))

956 s, c = _sincos2(-sca) # omg12a

957 # update spherical estimate of alp1 using omg12 instead of lam12

958 salp1 = p.cbet2 * s

959 calp1 = sbet12a - s * salp1 * p.sbet1 / (c + _1_0) # c = -c

960

961 # sanity check on starting guess. Backwards check allows NaN through.

962 salp1, calp1 = _norm2(salp1, calp1) if salp1 > 0 else (_1_0, _0_0)

963

964 return sig12, salp1, calp1, salp2, calp2, dnm

965

966 def _Lambda6(self, salp1, calp1, diffp, p):

967 '''(INTERNAL) Helper.

968

969 @return: 6-Tuple C{(lam12, sig12, salp2, calp2, domg12,

970 dlam12} and C{p.setsigs} updated.

971 '''

972 eF = self._eF

973 f1 = self.f1

974

975 if p.sbet1 == calp1 == 0: # PYCHOK no cover

976 # Break degeneracy of equatorial line

977 calp1 = -_TINY

978

979 # sin(alp1) * cos(bet1) = sin(alp0), # calp0 > 0

980 salp0, calp0 = _sin1cos2(salp1, calp1, p.sbet1, p.cbet1)

981 # tan(bet1) = tan(sig1) * cos(alp1)

982 # tan(omg1) = sin(alp0) * tan(sig1)

983 # = sin(bet1) * tan(alp1)

984 somg1 = salp0 * p.sbet1

985 comg1 = calp1 * p.cbet1

986 ssig1, csig1 = _norm2(p.sbet1, comg1)

987 # Without normalization we have schi1 = somg1

988 cchi1 = f1 * p.dn1 * comg1

989

990 # Enforce symmetries in the case abs(bet2) = -bet1.

991 # Need to be careful about this case, since this can

992 # yield singularities in the Newton iteration.

993 # sin(alp2) * cos(bet2) = sin(alp0)

994 salp2 = (salp0 / p.cbet2) if p.cbet2 != p.cbet1 else salp1

995 # calp2 = sqrt(1 - sq(salp2))

996 # = sqrt(sq(calp0) - sq(sbet2)) / cbet2

997 # and subst for calp0 and rearrange to give (choose

998 # positive sqrt to give alp2 in [0, PI/2]).

999 calp2 = fabs(calp1) if p.bet12 is None else (

1000 sqrt((calp1 * p.cbet1)**2 + p.bet12) / p.cbet2)

1001 # tan(bet2) = tan(sig2) * cos(alp2)

1002 # tan(omg2) = sin(alp0) * tan(sig2).

1003 somg2 = salp0 * p.sbet2

1004 comg2 = calp2 * p.cbet2

1005 ssig2, csig2 = _norm2(p.sbet2, comg2)

1006 # without normalization we have schi2 = somg2

1007 cchi2 = f1 * p.dn2 * comg2

1008

1009 # omg12 = omg2 - omg1, limit to [0, PI]

1010 somg12, comg12 = _sincos12(somg1, comg1, somg2, comg2, sineg0=True)

1011 # chi12 = chi2 - chi1, limit to [0, PI]

1012 schi12, cchi12 = _sincos12(somg1, cchi1, somg2, cchi2, sineg0=True)

1013

1014 p.setsigs(ssig1, csig1, ssig2, csig2)

1015 # sig12 = sig2 - sig1, limit to [0, PI]

1016 sig12 = _atan12(ssig1, csig1, ssig2, csig2, sineg0=True)

1017

1018 eta12 = self._eF_reset_cHe2_f1(calp0, salp0) * _2__PI # then ...

1019 eta12 *= fsum1f_(eF.deltaH(*p.sncndn2),

1020 -eF.deltaH(*p.sncndn1), sig12)

1021 # eta = chi12 - lam12

1022 lam12 = _atan12(p.slam12, p.clam12, schi12, cchi12) - eta12

1023 # domg12 = chi12 - omg12 - deta12

1024 domg12 = _atan12( somg12, comg12, schi12, cchi12) - eta12

1025

1026 dlam12 = NAN # dv > 0 in ._Newton6

1027 if diffp:

1028 d = calp2 * p.cbet2

1029 if d:

1030 _, dlam12, _, _, _ = self._Length5(sig12, Caps.REDUCEDLENGTH, p)

1031 dlam12 *= f1 / d

1032 elif p.sbet1:

1033 dlam12 = -f1 * p.dn1 * _2_0 / p.sbet1

1034

1035 # p.set_(deta12=-eta12, lam12=lam12)

1036 return lam12, sig12, salp2, calp2, domg12, dlam12

1037

1038 def _Length5(self, sig12, outmask, p):

1039 '''(INTERNAL) Return M{m12b = (reduced length) / self.b} and

1040 calculate M{s12b = distance / self.b} and M{m0}, the

1041 coefficient of secular term in expression for reduced

1042 length and the geodesic scales C{M12} and C{M21}.

1043

1044 @return: 5-Tuple C{(s12b, m12b, m0, M12, M21)}.

1045 '''

1046 s12b = m12b = m0 = M12 = M21 = NAN

1047

1048 Cs = Caps

1049 eF = self._eF

1050

1051 # outmask &= Cs._OUT_MASK

1052 if (outmask & Cs.DISTANCE):

1053 # Missing a factor of self.b

1054 s12b = eF.cE * _2__PI * fsum1f_(eF.deltaE(*p.sncndn2),

1055 -eF.deltaE(*p.sncndn1), sig12)

1056

1057 if (outmask & Cs._REDUCEDLENGTH_GEODESICSCALE):

1058 m0x = -eF.k2 * eF.cD * _2__PI

1059 J12 = -m0x * fsum1f_(eF.deltaD(*p.sncndn2),

1060 -eF.deltaD(*p.sncndn1), sig12)

1061 if (outmask & Cs.REDUCEDLENGTH):

1062 m0 = m0x

1063 # Missing a factor of self.b. Add parens around

1064 # (csig1 * ssig2) and (ssig1 * csig2) to ensure

1065 # accurate cancellation for coincident points.

1066 m12b = fsum1f_(p.dn2 * (p.csig1 * p.ssig2),

1067 -p.dn1 * (p.ssig1 * p.csig2),

1068 J12 * (p.csig1 * p.csig2))

1069 if (outmask & Cs.GEODESICSCALE):

1070 M12 = M21 = p.ssig1 * p.ssig2 + \

1071 p.csig1 * p.csig2

1072 t = (p.cbet1 - p.cbet2) * self.ep2 * \

1073 (p.cbet1 + p.cbet2) / (p.dn1 + p.dn2)

1074 M12 += (p.ssig2 * t + p.csig2 * J12) * p.ssig1 / p.dn1

1075 M21 -= (p.ssig1 * t + p.csig1 * J12) * p.ssig2 / p.dn2

1076

1077 return s12b, m12b, m0, M12, M21

1078

1079 def Line(self, lat1, lon1, azi1, caps=Caps.ALL, name=NN):

1080 '''Set up a L{GeodesicLineExact} to compute several points

1081 on a single geodesic.

1082

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

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

1085 @arg azi1: Azimuth at the first point (compass C{degrees}).

1086 @kwarg caps: Bit-or'ed combination of L{Caps} values specifying

1087 the capabilities the L{GeodesicLineExact} instance

1088 should possess, i.e., which quantities can be

1089 returnedby calls to L{GeodesicLineExact.Position}

1090 and L{GeodesicLineExact.ArcPosition}.

1091

1092 @return: A L{GeodesicLineExact} instance.

1093

1094 @note: If the point is at a pole, the azimuth is defined by keeping

1095 B{C{lon1}} fixed, writing C{B{lat1} = ±(90 − ε)}, and taking

1096 the limit C{ε → 0+}.

1097

1098 @see: C++ U{GeodesicExact.Line

1099 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicExact.html>}

1100 and Python U{Geodesic.Line<https://GeographicLib.SourceForge.io/Python/doc/code.html>}.

1101 '''

1102 return _GeodesicLineExact(self, lat1, lon1, azi1, caps, self._debug, name=name)

1103

1104 @Property_RO

1105 def n(self):

1106 '''Get the ellipsoid's I{3rd flattening} (C{float}), M{f / (2 - f) == (a - b) / (a + b)}.

1107 '''

1108 return self.ellipsoid.n

1109

1110 @Property_RO

1111 def _n_0_1(self):

1112 '''(INTERNAL) Cached once.

1113 '''

1114 return fabs(self.n) > _0_1

1115

1116 @Property_RO

1117 def _n6PI(self):

1118 '''(INTERNAL) Cached once.

1119 '''

1120 return fabs(self.n) * _6_0 * PI

1121

1122 def _Newton6(self, salp1, calp1, p):

1123 '''(INTERNAL) Split off from C{_GDictInverse} to reduce complexity/length.

1124

1125 @return: 6-Tuple C{(sig12, salp1, calp1, salp2, calp2, domg12)}

1126 and C{p.iter} and C{p.trip} updated.

1127 '''

1128 # This is a straightforward solution of f(alp1) = lambda12(alp1) -

1129 # lam12 = 0 with one wrinkle. f(alp) has exactly one root in the

1130 # interval (0, PI) and its derivative is positive at the root.

1131 # Thus f(alp) is positive for alp > alp1 and negative for alp < alp1.

1132 # During the course of the iteration, a range (alp1a, alp1b) is

1133 # maintained which brackets the root and with each evaluation of

1134 # f(alp) the range is shrunk, if possible. Newton's method is

1135 # restarted whenever the derivative of f is negative (because the

1136 # new value of alp1 is then further from the solution) or if the

1137 # new estimate of alp1 lies outside (0,PI); in this case, the new

1138 # starting guess is taken to be (alp1a + alp1b) / 2.

1139 salp1a = salp1b = _TINY

1140 calp1a, calp1b = _1_0, _N_1_0

1141 MAXIT1, TOL0 = _MAXIT1, _TOL0

1142 HALF, TOLb = _0_5, _TOLb

1143 tripb, TOLv = False, TOL0

1144 for i in range(_MAXIT2):

1145 # 1/4 meridian = 10e6 meter and random input,

1146 # estimated max error in nm (nano meter, by

1147 # checking Inverse problem by Direct).

1148 #

1149 # max iterations

1150 # log2(b/a) error mean sd

1151 # -7 387 5.33 3.68

1152 # -6 345 5.19 3.43

1153 # -5 269 5.00 3.05

1154 # -4 210 4.76 2.44

1155 # -3 115 4.55 1.87

1156 # -2 69 4.35 1.38

1157 # -1 36 4.05 1.03

1158 # 0 15 0.01 0.13

1159 # 1 25 5.10 1.53

1160 # 2 96 5.61 2.09

1161 # 3 318 6.02 2.74

1162 # 4 985 6.24 3.22

1163 # 5 2352 6.32 3.44

1164 # 6 6008 6.30 3.45

1165 # 7 19024 6.19 3.30

1166 v, sig12, salp2, calp2, \

1167 domg12, dv = self._Lambda6(salp1, calp1, i < MAXIT1, p)

1168

1169 # 2 * _TOL0 is approximately 1 ulp [0, PI]

1170 # reversed test to allow escape with NaNs

1171 if tripb or fabs(v) < TOLv:

1172 break

1173 # update bracketing values

1174 if v > 0 and (i > MAXIT1 or (calp1 / salp1) > (calp1b / salp1b)):

1175 salp1b, calp1b = salp1, calp1

1176 elif v < 0 and (i > MAXIT1 or (calp1 / salp1) < (calp1a / salp1a)):

1177 salp1a, calp1a = salp1, calp1

1178

1179 if i < MAXIT1 and dv > 0:

1180 dalp1 = -v / dv

1181 if fabs(dalp1) < PI:

1182 s, c = _sincos2(dalp1)

1183 # nalp1 = alp1 + dalp1

1184 s, c = _sincos12(-s, c, salp1, calp1)

1185 if s > 0:

1186 salp1, calp1 = _norm2(s, c)

1187 # in some regimes we don't get quadratic convergence

1188 # because slope -> 0. So use convergence conditions

1189 # based on epsilon instead of sqrt(epsilon)

1190 TOLv = TOL0 if fabs(v) > _TOL016 else _TOL08

1191 continue

1192

1193 # Either dv was not positive or updated value was outside

1194 # legal range. Use the midpoint of the bracket as the next

1195 # estimate. This mechanism is not needed for the WGS84

1196 # ellipsoid, but it does catch problems with more eccentric

1197 # ellipsoids. Its efficacy is such for the WGS84 test set

1198 # with the starting guess set to alp1 = 90 deg: the WGS84

1199 # test set: mean = 5.21, stdev = 3.93, max = 24 and WGS84

1200 # with random input: mean = 4.74, stdev = 0.99

1201 salp1, calp1 = _norm2((salp1a + salp1b) * HALF,

1202 (calp1a + calp1b) * HALF)

1203 tripb = fsum1f_(calp1a, -calp1, fabs(salp1a - salp1)) < TOLb or \

1204 fsum1f_(calp1b, -calp1, fabs(salp1b - salp1)) < TOLb

1205 TOLv = TOL0

1206

1207 else:

1208 raise GeodesicError(Fmt.no_convergence(v, TOLv), txt=repr(self)) # self.toRepr()

1209

1210 p.set_(iter=i, trip=tripb) # like .geodsolve._GDictInvoke: iter NOT iteration!

1211 return sig12, salp1, calp1, salp2, calp2, domg12

1212

1213 Polygon = Area # for C{geographiclib} compatibility

1214

1215 def _sinf1cos2d(self, lat):

1216 '''(INTERNAL) Helper, also for C{_G_GeodesicLineExact}.

1217 '''

1218 sbet, cbet = _sincos2d(lat)

1219 # ensure cbet1 = +epsilon at poles; doing the fix on beta means

1220 # that sig12 will be <= 2*tiny for two points at the same pole

1221 sbet, cbet = _norm2(sbet * self.f1, cbet)

1222 return sbet, max(_TINY, cbet)

1223

1224 def toStr(self, prec=6, sep=_COMMASPACE_, **unused): # PYCHOK signature

1225 '''Return this C{GeodesicExact} as string.

1226

1227 @kwarg prec: The C{float} precision, number of decimal digits (0..9).

1228 Trailing zero decimals are stripped for B{C{prec}} values

1229 of 1 and above, but kept for negative B{C{prec}} values.

1230 @kwarg sep: Separator to join (C{str}).

1231

1232 @return: Tuple items (C{str}).

1233 '''

1234 d = dict(ellipsoid=self.ellipsoid, C4order=self.C4order)

1235 return sep.join(pairs(d, prec=prec))

1236

1237

1238 class GeodesicLineExact(_GeodesicLineExact):

1239 '''A pure Python version of I{Karney}'s C++ class U{GeodesicLineExact

1240 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1GeodesicLineExact.html>},

1241 modeled after I{Karney}'s Python class U{geodesicline.GeodesicLine<https://GitHub.com/

1242 geographiclib/geographiclib-python>}.

1243 '''

1244

1245 def __init__(self, geodesic, lat1, lon1, azi1, caps=Caps.STANDARD, name=NN):

1246 '''New L{GeodesicLineExact} instance, allowing points to be found along

1247 a geodesic starting at C{(B{lat1}, B{lon1})} with azimuth B{C{azi1}}.

1248

1249 @arg geodesic: The geodesic to use (L{GeodesicExact}).

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

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

1252 @arg azi1: Azimuth at the first points (compass C{degrees}).

1253 @kwarg caps: Bit-or'ed combination of L{Caps} values specifying

1254 the capabilities the L{GeodesicLineExact} instance

1255 should possess, i.e., which quantities can be

1256 returned by calls to L{GeodesicLineExact.Position}

1257 and L{GeodesicLineExact.ArcPosition}.

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

1259

1260 @raise TypeError: Invalid B{C{geodesic}}.

1261 '''

1262 _xinstanceof(GeodesicExact, geodesic=geodesic)

1263 if (caps & Caps.LINE_OFF): # copy to avoid updates

1264 geodesic = geodesic.copy(deep=False, name=NN(_UNDER_, geodesic.name))

1265# _update_all(geodesic)

1266 _GeodesicLineExact.__init__(self, geodesic, lat1, lon1, azi1, caps, 0, name=name)

1267

1268

1269 def _Astroid(x, y):

1270 '''(INTERNAL) Solve M{k^4 + 2 * k^3 - (x^2 + y^2 - 1)

1271 * k^2 - (2 * k + 1) * y^2 = 0} for positive root k.

1272 '''

1273 p = x**2

1274 q = y**2

1275 r = fsumf_(_1_0, q, p, _N_2_0)

1276 if r > 0 or q:

1277 # avoid possible division by zero when r = 0

1278 # by multiplying s and t by r^3 and r, resp.

1279 S = p * q / _4_0 # S = r^3 * s

1280 if r:

1281 r = r / _6_0 # /= chokes PyChecker

1282 r3 = r**3

1283 T3 = r3 + S

1284 # discriminant of the quadratic equation for T3 is

1285 # zero on the evolute curve p^(1/3) + q^(1/3) = 1

1286 d = (r3 + T3) * S

1287 if d < 0:

1288 # T is complex, but u is defined for a real result

1289 a = atan2(sqrt(-d), -T3) / _3_0

1290 # There are 3 possible cube roots, choose the one which

1291 # avoids cancellation. Note d < 0 implies that r < 0.

1292 u = (cos(a) * _2_0 + _1_0) * r

1293 else:

1294 # pick the sign on the sqrt to maximize abs(T3) to

1295 # minimize loss of precision due to cancellation.

1296 if d:

1297 T3 += _copysign(sqrt(d), T3) # T3 = (r * t)^3

1298 # _cbrt always returns the real root, _cbrt(-8) = -2

1299 u = _cbrt(T3) # T = r * t

1300 if u: # T can be zero; but then r2 / T -> 0

1301 u += r**2 / u

1302 u += r

1303 elif S: # d == T3**2 == S**2: sqrt(d) == abs(S) == abs(T3)

1304 u = _cbrt(S * _2_0) # == T3 + _copysign(abs(S), T3)

1305 else:

1306 u = _0_0

1307 v = _hypot(u, y) # sqrt(u**2 + q)

1308 # avoid loss of accuracy when u < 0

1309 u = (q / (v - u)) if u < 0 else (v + u)

1310 w = (u - q) / (v + v) # positive?

1311 # rearrange expression for k to avoid loss of accuracy due to

1312 # subtraction, division by 0 impossible because u > 0, w >= 0

1313 k = u / (sqrt(w**2 + u) + w) # guaranteed positive

1314

1315 else: # q == 0 && r <= 0

1316 # y = 0 with |x| <= 1. Handle this case directly, for

1317 # y small, positive root is k = abs(y) / sqrt(1 - x^2)

1318 k = _0_0

1319

1320 return k

1321

1322

1323 def _C4coeffs(nC4): # in .geodesicx.__main__

1324 '''(INTERNAL) Get the C{C4_24}, C{_27} or C{_30} series coefficients.

1325 '''

1326 try: # from pygeodesy.geodesicx._C4_xx import _coeffs_xx as _coeffs

1327 _C4_xx = _DOT_(_MODS.geodesicx.__name__, _UNDER_('_C4', nC4))

1328 _coeffs = _MODS.getattr(_C4_xx, _UNDER_('_coeffs', nC4))

1329 except (AttributeError, ImportError, TypeError) as x:

1330 raise GeodesicError(nC4=nC4, cause=x)

1331 n = _xnC4(nC4=nC4)

1332 if len(_coeffs) != n: # double check

1333 raise GeodesicError(_coeffs=len(_coeffs), _xnC4=n, nC4=nC4)

1334 return _coeffs

1335

1336

1337__all__ += _ALL_DOCS(GeodesicExact, GeodesicLineExact)

1338

1339# **) MIT License

1340#

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

1342#

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

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

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

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

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

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

1349#

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

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

1352#

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

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

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

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

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

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

1359# OTHER DEALINGS IN THE SOFTWARE.