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-2022)

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.fsums import fsum_, fsum1_

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

47 _sincos12, _sin1cos2, _xnC4

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

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

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

51 _a_ellipsoid, _EWGS84, GDict, GeodesicError, _fix90, \

52 _hypot, _K_2_0, _norm2, _norm180, _polynomial, \

53 _signBit, _sincos2, _sincos2d, _sincos2de, _unsigned2

54 from pygeodesy.lazily import _ALL_DOCS, _ALL_MODS as _MODS

55 from pygeodesy.namedTuples import Destination3Tuple, Distance3Tuple

56 from pygeodesy.props import deprecated_Property, Property, Property_RO

57 from pygeodesy.streprs import Fmt, pairs

58 from pygeodesy.utily import atan2d as _atan2d_reverse, unroll180, wrap360

59

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

61

62__all__ = ()

63__version__ = '23.04.11'

64

65_MAXIT1 = 20

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

67

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

69# case 52.784459512564 0 -52.784459512563990912 179.634407464943777557

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

71_TOL0 = EPS

72_TOL1 = _TOL0 * -200 # negative

73_TOL2 = _EPSqrt # == sqrt(_TOL0)

74_TOL3 = _TOL2 * _0_1

75_TOLb = _TOL2 * _TOL0 # Check on bisection interval

76_THR1 = _TOL2 * _1000_0 + _1_0

77

78_TINY3 = _TINY * _3_0

79_TOL08 = _TOL0 * _8_0

80_TOL016 = _TOL0 * _16_0

81

82

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

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

85 '''

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

87

88

89 def _eTOL2(f):

90 # Using the auxiliary sphere solution with dnm computed at

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

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

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

94

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

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

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

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

99

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

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

102 # nearly spherical case.

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

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

105

106

107 class _PDict(GDict):

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

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

110 '''

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

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

113 '''

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

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

116

117 def toGDict(self): # PYCHOK no cover

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

119 '''

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

121 return GDict(rest)

122

123 return _rest(**self)

124

125

126 class GeodesicExact(_GeodesicBase):

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

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

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

130 geographiclib/geographiclib-python>}.

131 '''

132 _E = _EWGS84

133 _nC4 = 30 # default C4order

134

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

136 C4Order=None): # for backward compatibility

137 '''New L{GeodesicExact} instance.

138

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

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

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

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

143 is specified as C{scalar}.

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

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

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

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

148

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

150 '''

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

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

153

154 if name:

155 self.name = name

156 if C4order: # XXX private copy, always?

157 self.C4order = C4order

158 elif C4Order: # for backward compatibility

159 self.C4Order = C4Order

160

161 @Property_RO

162 def a(self):

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

164 '''

165 return self.ellipsoid.a

166

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

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

169

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

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

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

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

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

175 the quantities to be returned.

176

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

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

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

180

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

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

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

184 '''

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

186

187 def ArcDirectLine(self, lat1, lon1, azi1, a12, caps):

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

189

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

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

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

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

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

195 the capabilities the L{GeodesicLineExact} instance

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

197 returned by calls to L{GeodesicLineExact.Position}

198 and L{GeodesicLineExact.ArcPosition}.

199

200 @return: A L{GeodesicLineExact} instance.

201

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

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

204

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

206

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

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

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

210 '''

211 return self._GenDirectLine(lat1, lon1, azi1, True, a12, caps)

212

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

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

215 perimeter of a polygon.

216

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

218 area and perimeter (C{bool}).

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

220

221 @return: A L{GeodesicAreaExact} instance.

222

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

224 to the returned L{GeodesicAreaExact} instance.

225 '''

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

227 name=name or self.name)

228 if self.debug:

229 gaX.verbose = True

230 return gaX

231

232 @Property_RO

233 def b(self):

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

235 '''

236 return self.ellipsoid.b

237

238 @Property_RO

239 def c2x(self):

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

241 '''

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

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

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

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

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

247 return self.ellipsoid.c2x

248

249 c2 = c2x # in this particular case

250

251 def C4f(self, eps):

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

253

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

255

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

257 '''

258 def _c4(nC4, C4x):

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

260 _p = _polynomial

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

262 j = i + r

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

264 x *= e

265 i = j

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

267

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

269

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

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

272 '''

273 return self.C4f(k2 / fsum_(_2_0, sqrt(k2 + _1_0) * _2_0, k2))

274

275 @Property

276 def C4order(self):

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

278 '''

279 return self._nC4

280

281 @C4order.setter # PYCHOK .setter!

282 def C4order(self, order):

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

284

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

286 '''

287 _xnC4(C4order=order)

288 if self._nC4 != order:

289 GeodesicExact._C4x._update(self)

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

291 self._nC4 = order

292

293 @deprecated_Property

294 def C4Order(self):

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

296 '''

297 return self.C4order

298

299 @C4Order.setter # PYCHOK .setter!

300 def C4Order(self, order):

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

302 '''

303 _xnC4(C4Order=order)

304 self.C4order = order

305

306 def _coeffs(self, nC4):

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

308 '''

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

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

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

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

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

314 n = _xnC4(nC4=nC4)

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

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

317 return _coeffs

318

319 @Property_RO

320 def _C4x(self):

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

322

323 @see: Property L{C4order}.

324 '''

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

326 def _C4(nC4):

327 i, n, cs = 0, self.n, self._coeffs(nC4)

328 _p = _polynomial

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

330 for j in range(1, r):

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

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

333 i = j + 1

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

335

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

337

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

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

340

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

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

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

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

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

346 the quantities to be returned.

347

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

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

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

351

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

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

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

355 '''

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

357

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

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

360 (final bearing) in C{degrees}.

361

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

363 '''

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

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

366

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

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

369

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

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

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

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

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

375 the capabilities the L{GeodesicLineExact} instance

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

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

378

379 @return: A L{GeodesicLineExact} instance.

380

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

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

383

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

385

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

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

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

389 '''

390 return self._GenDirectLine(lat1, lon1, azi1, False, s12, caps)

391

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

393 '''(INTERNAL) Helper.

394 '''

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

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

397 else:

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

399 return dn

400

401 @Property_RO

402 def e2(self):

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

404 '''

405 return self.ellipsoid.e2

406

407 @Property_RO

408 def _e2a2(self):

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

410 '''

411 return self.e2 * self.ellipsoid.a2

412

413 @Property_RO

414 def _e2_f1(self):

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

416 '''

417 return self.e2 / self.f1

418

419 @Property_RO

420 def _eF(self):

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

422 '''

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

424

425 def _eF_reset_cHe2_f1(self, x, y):

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

427 '''

428 self._eF_reset_k2(x)

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

430

431 def _eF_reset_k2(self, x):

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

433 '''

434 ep2 = self.ep2

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

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

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

438 return k2

439

440 @Property_RO

441 def ellipsoid(self):

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

443 '''

444 return self._E

445

446 @Property_RO

447 def ep2(self):

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

449 '''

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

451

452 e22 = ep2 # for ellipsoid compatibility

453

454 @Property_RO

455 def _eTOL2(self):

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

457 '''

458 return _eTOL2(self.f)

459

460 @Property_RO

461 def f(self):

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

463 '''

464 return self.ellipsoid.f

465

466 flattening = f

467

468 @Property_RO

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

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

471 '''

472 return self.ellipsoid.f1

473

474 @Property_RO

475 def _f180(self):

476 '''(INTERNAL) Cached/memoized.

477 '''

478 return self.f * _180_0

479

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

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

482

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

484 '''

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

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

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

488

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

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

491

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

493 '''

494 Cs = Caps

495 if self._debug: # PYCHOK no cover

496 outmask |= Cs._DEBUG_INVERSE & self._debug

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

498 # compute longitude difference carefully (with _diff182):

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

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

501 lon12, lon12s = _diff182(lon1, lon2)

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

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

504 r = GDict(lon1=lon1, lon2=fsum_(lon1, lon12, lon12s))

505 else:

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

507 if _K_2_0: # GeographicLib 2.0

508 # make longitude difference positive

509 lon12, lon_ = _unsigned2(lon12)

510 if lon_:

511 lon12s = -lon12s

512 lam12 = radians(lon12)

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

514 slam12, clam12 = _sincos2de(lon12, lon12s)

515 # supplementary longitude difference

516 lon12s = fsum_(_180_0, -lon12, -lon12s)

517 else: # GeographicLib 1.52

518 # make longitude difference positive and if very close

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

520 if lon12 < 0: # _signBit(lon12)

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

522 lon12s = _around(fsum_(_180_0, -lon12, lon12s))

523 else:

524 lon_, lon12 = False, _around(lon12)

525 lon12s = _around(fsum_(_180_0, -lon12, -lon12s))

526 lam12 = radians(lon12)

527 if lon12 > _90_0:

528 slam12, clam12 = _sincos2d(lon12s)

529 clam12 = -clam12

530 else:

531 slam12, clam12 = _sincos2(lam12)

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

533 lat1 = _around(_fix90(lat1))

534 lat2 = _around(_fix90(lat2))

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

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

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

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

539 if swap_:

540 lat1, lat2 = lat2, lat1

541 lon_ = not lon_

542 if _signBit(lat1):

543 lat_ = False # note, False

544 else: # make lat1 <= -0

545 lat_ = True # note, True

546 lat1, lat2 = -lat1, -lat2

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

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

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

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

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

552 # this enforces some symmetries in the results returned.

553

554 # Initialize for the meridian. No longitude calculation is

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

556 sbet1, cbet1 = self._sinf1cos2d(lat1)

557 sbet2, cbet2 = self._sinf1cos2d(lat2)

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

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

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

561 # in assigning calp2 in _Lambda6. Sometimes these quantities

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

563 # example where is is necessary is the inverse problem

564 # 48.522876735459 0 -48.52287673545898293 179.599720456223079643

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

566 if cbet1 < -sbet1:

567 if cbet2 == cbet1:

568 sbet2 = copysign(sbet1, sbet2)

569 elif fabs(sbet2) == -sbet1:

570 cbet2 = cbet1

571

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

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

574

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

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

577 # Endpoints are on a single full meridian,

578 # so the geodesic might lie on a meridian.

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

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

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

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

583 # sig12 = sig2 - sig1

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

585 s12x, m12x, _, \

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

587 # Add the check for sig12 since zero length geodesics

588 # might yield m12 < 0. Test case was

589 # echo 20.001 0 20.001 0 | GeodSolve -i

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

591 # geodesic which is not a shortest path.

592 if m12x >= 0 or sig12 < _1_0:

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

594 # Prevent negative s12 or m12 from geographiclib 1.52

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

596 sig12 = m12x = s12x = _0_0

597 else:

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

599 _meridian = False

600 C = 1

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

602 # _meridian = True

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

604

605 if _meridian:

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

607 if _b: # Geodesic runs along equator

608 calp1 = calp2 = _0_0

609 salp1 = salp2 = _1_0

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

611 somg12, comg12 = _sincos2(sig12)

612 m12x = self.b * somg12

613 s12x = self.a * lam12

614 M12 = M21 = comg12

615 a12 = lon12 / self.f1

616 C = 2

617 else:

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

619 # meridian and geodesic is neither meridional or equatorial.

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

621 # Figure a starting point for Newton's method

622 sig12, salp1, calp1, \

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

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

625 # pre-compute the constant _Lambda6 term, once

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

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

628 ((sbet1 + sbet2) * (sbet1 - sbet2))))

629 sig12, salp1, calp1, \

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

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

632 if (outmask & Cs.AREA):

633 # omg12 = lam12 - domg12

634 s, c = _sincos2(domg12)

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

636 C = 3 # Newton

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

638 C = 4 # Short lines

639 s, c = _sincos2(sig12 / dnm)

640 m12x = dnm**2 * s

641 s12x = dnm * sig12

642 M12 = M21 = c

643 if (outmask & Cs.AREA):

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

645

646 else: # _meridian is False

647 somg12 = comg12 = NAN

648

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

650

651 if (outmask & Cs.DISTANCE):

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

653

654 if (outmask & Cs.REDUCEDLENGTH):

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

656

657 if (outmask & Cs.GEODESICSCALE):

658 if swap_:

659 M12, M21 = M21, M12

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

661 M21=unsigned0(M21))

662

663 if (outmask & Cs.AREA):

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

665 salp2, calp2,

666 somg12, comg12, p)

667 if _xor(swap_, lat_, lon_):

668 S12 = -S12

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

670

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

672 if swap_:

673 salp1, salp2 = salp2, salp1

674 calp1, calp2 = calp2, calp1

675 if _xor(swap_, lon_):

676 salp1, salp2 = -salp1, -salp2

677 if _xor(swap_, lat_):

678 calp1, calp2 = -calp1, -calp2

679

680 if (outmask & Cs.AZIMUTH):

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

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

683 if (outmask & Cs._SALPs_CALPs):

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

685 salp2=salp2, calp2=calp2)

686

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

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

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

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

691 c2=E.c2, c2x=self.c2x,

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

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

694 p.update(r) # r overrides p

695 r = p.toGDict()

696 return self._iter2tion(r, p)

697

698 def _GenDirect(self, lat1, lon1, azi1, arcmode, s12_a12, outmask):

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

700

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

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

703 '''

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

705 return r.toDirect9Tuple()

706

707 def _GenDirectLine(self, lat1, lon1, azi1, arcmode, s12_a12, caps):

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

709

710 @return: A L{GeodesicLineExact} instance.

711 '''

712 azi1 = _norm180(azi1)

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

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

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

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

717 self._debug, s, c)._GenSet(arcmode, s12_a12)

718

719 def _GenInverse(self, lat1, lon1, lat2, lon2, outmask):

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

721

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

723 m12, M12, M21, S12)}.

724 '''

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

726 return r.toInverse10Tuple()

727

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

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

730

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

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

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

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

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

736 the quantities to be returned.

737

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

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

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

741

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

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

744

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

746

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

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

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

750 '''

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

752

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

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

755 '''

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

757 # and .HeightIDWkarney._distances

758 _, lon2 = unroll180(lon1, lon2, wrap=wrap) # self.LONG_UNROLL

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

760

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

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

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

764

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

766 '''

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

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

769 iteration=r.iteration)

770

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

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

773

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

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

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

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

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

779 the capabilities the L{GeodesicLineExact} instance

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

781 returned by calls to L{GeodesicLineExact.Position}

782 and L{GeodesicLineExact.ArcPosition}.

783

784 @return: A L{GeodesicLineExact} instance.

785

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

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

788

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

790

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

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

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

794 '''

795 Cs = Caps

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

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

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

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

800 self._debug, r.salp1, r.calp1)._GenSet(True, r.a12)

801

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

803 salp2, calp2,

804 somg12, comg12, p):

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

806

807 @return: Area C{S12}.

808 '''

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

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

811 A4 = calp0 * salp0

812 if A4:

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

814 k2 = calp0**2 * self.ep2

815 C4a = self._C4f_k2(k2)

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

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

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

819 A4 *= self._e2a2

820 S12 = A4 * (B42 - B41)

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

822 A4 = B41 = B42 = k2 = S12 = _0_0

823

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

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

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

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

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

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

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

831 dbet1 = p.cbet1 + _1_0

832 dbet2 = p.cbet2 + _1_0

833 domg12 = comg12 + _1_0

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

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

836 alp12 = _2_0 * atan2(salp12, calp12)

837 else:

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

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

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

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

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

843 # Following ensures the correct behavior.

844 if salp12 == 0 and calp12 < 0:

845 alp12 = _copysign(PI, calp1)

846 else:

847 alp12 = atan2(salp12, calp12)

848

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

850 return S12 + self.c2x * alp12

851

852 def _InverseStart6(self, lam12, p):

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

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

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

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

857

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

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

860 '''

861 sig12 = None # use Newton

862 salp1 = calp1 = salp2 = calp2 = dnm = NAN

863

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

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

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

867 if shortline:

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

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

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

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

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

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

874 else:

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

876

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

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

879

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

881 s = somg12**2 / c

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

883 salp1 = p.cbet2 * somg12

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

885

886 ssig12 = _hypot(salp1, calp1)

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

888

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

890 t = c if comg12 < 0 else s

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

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

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

894

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

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

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

898

899 else:

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

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

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

903 f = self.f

904 if f < 0: # PYCHOK no cover

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

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

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

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

909 Caps.REDUCEDLENGTH, p)

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

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

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

913 y = lam12x / sca

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

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

916 x = lam12x / sca # dlon

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

918

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

920 if f < 0: # PYCHOK no cover

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

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

923 else:

924 salp1 = min( _1_0, -x)

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

926 else:

927 # Estimate alp1, by solving the astroid problem.

928 #

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

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

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

932 #

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

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

935 # number of Newton iterations for astroid cases from 2.24

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

937 # number of iterations are as follows:

938 #

939 # change percent

940 # 1 5

941 # 0 78

942 # -1 16

943 # -2 0.6

944 # -3 0.04

945 # -4 0.002

946 #

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

948 # estimating alp1 directly, n = number of iterations

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

950 #

951 # iter m n

952 # 0 148 186

953 # 1 13046 13845

954 # 2 93315 102225

955 # 3 36189 32341

956 # 4 5396 7

957 # 5 455 1

958 # 6 56 0

959 #

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

961 k = _Astroid(x, y)

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

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

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

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

966 salp1 = p.cbet2 * s

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

968

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

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

971

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

973

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

975 '''(INTERNAL) Helper.

976

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

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

979 '''

980 eF = self._eF

981 f1 = self.f1

982

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

984 # Break degeneracy of equatorial line

985 calp1 = -_TINY

986

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

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

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

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

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

992 somg1 = salp0 * p.sbet1

993 comg1 = calp1 * p.cbet1

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

995 # Without normalization we have schi1 = somg1

996 cchi1 = f1 * p.dn1 * comg1

997

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

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

1000 # yield singularities in the Newton iteration.

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

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

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

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

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

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

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

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

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

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

1011 somg2 = salp0 * p.sbet2

1012 comg2 = calp2 * p.cbet2

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

1014 # without normalization we have schi2 = somg2

1015 cchi2 = f1 * p.dn2 * comg2

1016

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

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

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

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

1021

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

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

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

1025

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

1027 eta12 *= fsum1_(eF.deltaH(*p.sncndn2),

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

1029 # eta = chi12 - lam12

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

1031 # domg12 = chi12 - omg12 - deta12

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

1033

1034 dlam12 = NAN # dv > 0 in ._Newton6

1035 if diffp:

1036 d = calp2 * p.cbet2

1037 if d:

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

1039 dlam12 *= f1 / d

1040 elif p.sbet1:

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

1042

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

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

1045

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

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

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

1049 coefficient of secular term in expression for reduced

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

1051

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

1053 '''

1054 s12b = m12b = m0 = M12 = M21 = NAN

1055

1056 Cs = Caps

1057 eF = self._eF

1058

1059 # outmask &= Cs._OUT_MASK

1060 if (outmask & Cs.DISTANCE):

1061 # Missing a factor of self.b

1062 s12b = eF.cE * _2__PI * fsum1_(eF.deltaE(*p.sncndn2),

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

1064

1065 if (outmask & Cs._REDUCEDLENGTH_GEODESICSCALE):

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

1067 J12 = -m0x * fsum1_(eF.deltaD(*p.sncndn2),

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

1069 if (outmask & Cs.REDUCEDLENGTH):

1070 m0 = m0x

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

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

1073 # accurate cancellation for coincident points.

1074 m12b = fsum1_(p.dn2 * (p.csig1 * p.ssig2),

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

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

1077 if (outmask & Cs.GEODESICSCALE):

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

1079 p.csig1 * p.csig2

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

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

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

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

1084

1085 return s12b, m12b, m0, M12, M21

1086

1087 def Line(self, lat1, lon1, azi1, caps=Caps.ALL):

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

1089 on a single geodesic.

1090

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

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

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

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

1095 the capabilities the L{GeodesicLineExact} instance

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

1097 returnedby calls to L{GeodesicLineExact.Position}

1098 and L{GeodesicLineExact.ArcPosition}.

1099

1100 @return: A L{GeodesicLineExact} instance.

1101

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

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

1104 the limit C{ε → 0+}.

1105

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

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

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

1109 '''

1110 return _GeodesicLineExact(self, lat1, lon1, azi1, caps, self._debug)

1111

1112 @Property_RO

1113 def n(self):

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

1115 '''

1116 return self.ellipsoid.n

1117

1118 @Property_RO

1119 def _n_0_1(self):

1120 '''(INTERNAL) Cached once.

1121 '''

1122 return fabs(self.n) > _0_1

1123

1124 @Property_RO

1125 def _n6PI(self):

1126 '''(INTERNAL) Cached once.

1127 '''

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

1129

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

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

1132

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

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

1135 '''

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

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

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

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

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

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

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

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

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

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

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

1147 salp1a = salp1b = _TINY

1148 calp1a, calp1b = _1_0, _N_1_0

1149 MAXIT1, TOL0 = _MAXIT1, _TOL0

1150 HALF, TOLb = _0_5, _TOLb

1151 tripb, TOLv = False, TOL0

1152 for i in range(_MAXIT2):

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

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

1155 # checking Inverse problem by Direct).

1156 #

1157 # max iterations

1158 # log2(b/a) error mean sd

1159 # -7 387 5.33 3.68

1160 # -6 345 5.19 3.43

1161 # -5 269 5.00 3.05

1162 # -4 210 4.76 2.44

1163 # -3 115 4.55 1.87

1164 # -2 69 4.35 1.38

1165 # -1 36 4.05 1.03

1166 # 0 15 0.01 0.13

1167 # 1 25 5.10 1.53

1168 # 2 96 5.61 2.09

1169 # 3 318 6.02 2.74

1170 # 4 985 6.24 3.22

1171 # 5 2352 6.32 3.44

1172 # 6 6008 6.30 3.45

1173 # 7 19024 6.19 3.30

1174 v, sig12, salp2, calp2, \

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

1176

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

1178 # reversed test to allow escape with NaNs

1179 if tripb or fabs(v) < TOLv:

1180 break

1181 # update bracketing values

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

1183 salp1b, calp1b = salp1, calp1

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

1185 salp1a, calp1a = salp1, calp1

1186

1187 if i < MAXIT1 and dv > 0:

1188 dalp1 = -v / dv

1189 if fabs(dalp1) < PI:

1190 s, c = _sincos2(dalp1)

1191 # nalp1 = alp1 + dalp1

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

1193 if s > 0:

1194 salp1, calp1 = _norm2(s, c)

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

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

1197 # based on epsilon instead of sqrt(epsilon)

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

1199 continue

1200

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

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

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

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

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

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

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

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

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

1210 (calp1a + calp1b) * HALF)

1211 tripb = fsum1_(calp1a, -calp1, fabs(salp1a - salp1)) < TOLb or \

1212 fsum1_(calp1b, -calp1, fabs(salp1b - salp1)) < TOLb

1213 TOLv = TOL0

1214

1215 else:

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

1217

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

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

1220

1221 Polygon = Area # for C{geographiclib} compatibility

1222

1223 def _sinf1cos2d(self, lat):

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

1225 '''

1226 sbet, cbet = _sincos2d(lat)

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

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

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

1230 return sbet, max(_TINY, cbet)

1231

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

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

1234

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

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

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

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

1239

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

1241 '''

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

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

1244

1245

1246 class GeodesicLineExact(_GeodesicLineExact):

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

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

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

1250 geographiclib/geographiclib-python>}.

1251 '''

1252

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

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

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

1256

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

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

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

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

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

1262 the capabilities the L{GeodesicLineExact} instance

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

1264 returned by calls to L{GeodesicLineExact.Position}

1265 and L{GeodesicLineExact.ArcPosition}.

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

1267

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

1269 '''

1270 _xinstanceof(GeodesicExact, geodesic=geodesic)

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

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

1273# _update_all(geodesic)

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

1275

1276

1277 def _Astroid(x, y):

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

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

1280 '''

1281 p = x**2

1282 q = y**2

1283 r = fsum_(_1_0, q, p, _N_2_0, floats=True)

1284 if q or r > 0:

1285 r = r / _6_0 # /= chokes PyChecker

1286 # avoid possible division by zero when r = 0

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

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

1289 r3 = r**3

1290 T3 = r3 + S

1291 # discriminant of the quadratic equation for T3 is

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

1293 d = S * (S + r3 * _2_0)

1294 if d < 0:

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

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

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

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

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

1300 else:

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

1302 # minimize loss of precision due to cancellation.

1303 if d:

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

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

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

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

1308 u += r**2 / u

1309 u += r

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

1311 # avoid loss of accuracy when u < 0

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

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

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

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

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

1317

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

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

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

1321 k = _0_0

1322

1323 return k

1324

1325

1326__all__ += _ALL_DOCS(GeodesicExact, GeodesicLineExact)

1327

1328# **) MIT License

1329#

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

1331#

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

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

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

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

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

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

1338#

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

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

1341#

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

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

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

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

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

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

1348# OTHER DEALINGS IN THE SOFTWARE.