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:Karney@Alum.MIT.edu>} (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.ellipsoids import _EWGS84 # from .karney

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

47 from pygeodesy.fsums import fsumf_, fsum1f_

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

49 _sincos12, _sin1cos2, _xnC4

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

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

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

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

54 _norm2, _norm180, _polynomial, _signBit, _sincos2, \

55 _sincos2d, _sincos2de, _unsigned2, _a_ellipsoid

56 from pygeodesy.lazily import _ALL_DOCS, _ALL_MODS as _MODS

57 from pygeodesy.namedTuples import Destination3Tuple, Distance3Tuple

58 from pygeodesy.props import deprecated_Property, Property, Property_RO

59 from pygeodesy.streprs import Fmt, pairs

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

61

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

63

64__all__ = ()

65__version__ = '23.08.20'

66

67_MAXIT1 = 20

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

69

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

71# case 52.784459512564 0 -52.784459512563990912 179.634407464943777557

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

73_TOL0 = EPS

74_TOL1 = _TOL0 * -200 # negative

75_TOL2 = _EPSqrt # == sqrt(_TOL0)

76_TOL3 = _TOL2 * _0_1

77_TOLb = _TOL2 * _TOL0 # Check on bisection interval

78_THR1 = _TOL2 * _1000_0 + _1_0

79

80_TINY3 = _TINY * _3_0

81_TOL08 = _TOL0 * _8_0

82_TOL016 = _TOL0 * _16_0

83

84

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

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

87 '''

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

89

90

91 def _eTOL2(f):

92 # Using the auxiliary sphere solution with dnm computed at

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

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

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

96

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

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

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

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

101

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

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

104 # nearly spherical case.

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

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

107

108

109 class _PDict(GDict):

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

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

112 '''

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

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

115 '''

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

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

118

119 def toGDict(self): # PYCHOK no cover

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

121 '''

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

123 return GDict(rest)

124

125 return _rest(**self)

126

127

128 class GeodesicExact(_GeodesicBase):

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

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

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

132 geographiclib/geographiclib-python>}.

133 '''

134 _E = _EWGS84

135 _nC4 = 30 # default C4order

136

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

138 C4Order=None): # for backward compatibility

139 '''New L{GeodesicExact} instance.

140

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

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

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

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

145 is specified as C{scalar}.

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

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

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

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

150

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

152 '''

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

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

155

156 if name:

157 self.name = name

158 if C4order: # XXX private copy, always?

159 self.C4order = C4order

160 elif C4Order: # for backward compatibility

161 self.C4Order = C4Order

162

163 @Property_RO

164 def a(self):

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

166 '''

167 return self.ellipsoid.a

168

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

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

171

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

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

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

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

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

177 the quantities to be returned.

178

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

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

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

182

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

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

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

186 '''

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

188

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

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

191

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

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

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

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

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

197 the capabilities the L{GeodesicLineExact} instance

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

199 returned by calls to L{GeodesicLineExact.Position}

200 and L{GeodesicLineExact.ArcPosition}.

201

202 @return: A L{GeodesicLineExact} instance.

203

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

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

206

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

208

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

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

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

212 '''

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

214

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

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

217 perimeter of a polygon.

218

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

220 area and perimeter (C{bool}).

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

222

223 @return: A L{GeodesicAreaExact} instance.

224

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

226 to the returned L{GeodesicAreaExact} instance.

227 '''

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

229 name=name or self.name)

230 if self.debug:

231 gaX.verbose = True

232 return gaX

233

234 @Property_RO

235 def b(self):

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

237 '''

238 return self.ellipsoid.b

239

240 @Property_RO

241 def c2x(self):

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

243 '''

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

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

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

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

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

249 return self.ellipsoid.c2x

250

251 c2 = c2x # in this particular case

252

253 def C4f(self, eps):

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

255

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

257

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

259 '''

260 def _c4(nC4, C4x):

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

262 _p = _polynomial

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

264 j = i + r

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

266 x *= e

267 i = j

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

269

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

271

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

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

274 '''

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

276

277 @Property

278 def C4order(self):

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

280 '''

281 return self._nC4

282

283 @C4order.setter # PYCHOK .setter!

284 def C4order(self, order):

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

286

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

288 '''

289 _xnC4(C4order=order)

290 if self._nC4 != order:

291 GeodesicExact._C4x._update(self)

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

293 self._nC4 = order

294

295 @deprecated_Property

296 def C4Order(self):

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

298 '''

299 return self.C4order

300

301 @C4Order.setter # PYCHOK .setter!

302 def C4Order(self, order):

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

304 '''

305 _xnC4(C4Order=order)

306 self.C4order = order

307

308 @Property_RO

309 def _C4x(self):

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

311

312 @see: Property L{C4order}.

313 '''

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

315 def _C4(nC4):

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

317 _p = _polynomial

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

319 for j in range(1, r):

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

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

322 i = j + 1

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

324

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

326

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

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

329

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

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

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

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

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

335 the quantities to be returned.

336

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

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

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

340

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

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

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

344 '''

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

346

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

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

349 (final bearing) in C{degrees}.

350

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

352 '''

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

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

355

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

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

358

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

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

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

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

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

364 the capabilities the L{GeodesicLineExact} instance

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

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

367

368 @return: A L{GeodesicLineExact} instance.

369

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

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

372

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

374

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

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

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

378 '''

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

380

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

382 '''(INTERNAL) Helper.

383 '''

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

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

386 else:

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

388 return dn

389

390 @Property_RO

391 def e2(self):

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

393 '''

394 return self.ellipsoid.e2

395

396 @Property_RO

397 def _e2a2(self):

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

399 '''

400 return self.e2 * self.ellipsoid.a2

401

402 @Property_RO

403 def _e2_f1(self):

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

405 '''

406 return self.e2 / self.f1

407

408 @Property_RO

409 def _eF(self):

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

411 '''

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

413

414 def _eF_reset_cHe2_f1(self, x, y):

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

416 '''

417 self._eF_reset_k2(x)

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

419

420 def _eF_reset_k2(self, x):

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

422 '''

423 ep2 = self.ep2

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

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

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

427 return k2

428

429 @Property_RO

430 def ellipsoid(self):

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

432 '''

433 return self._E

434

435 @Property_RO

436 def ep2(self):

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

438 '''

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

440

441 e22 = ep2 # for ellipsoid compatibility

442

443 @Property_RO

444 def _eTOL2(self):

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

446 '''

447 return _eTOL2(self.f)

448

449 @Property_RO

450 def f(self):

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

452 '''

453 return self.ellipsoid.f

454

455 flattening = f

456

457 @Property_RO

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

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

460 '''

461 return self.ellipsoid.f1

462

463 @Property_RO

464 def _f180(self):

465 '''(INTERNAL) Cached/memoized.

466 '''

467 return self.f * _180_0

468

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

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

471

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

473 '''

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

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

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

477

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

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

480

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

482 '''

483 Cs = Caps

484 if self._debug: # PYCHOK no cover

485 outmask |= Cs._DEBUG_INVERSE & self._debug

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

487 # compute longitude difference carefully (with _diff182):

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

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

490 lon12, lon12s = _diff182(lon1, lon2)

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

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

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

494 else:

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

496 if _K_2_0: # GeographicLib 2.0

497 # make longitude difference positive

498 lon12, lon_ = _unsigned2(lon12)

499 if lon_:

500 lon12s = -lon12s

501 lam12 = radians(lon12)

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

503 slam12, clam12 = _sincos2de(lon12, lon12s)

504 # supplementary longitude difference

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

506 else: # GeographicLib 1.52

507 # make longitude difference positive and if very close

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

509 if lon12 < 0: # _signBit(lon12)

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

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

512 else:

513 lon_, lon12 = False, _around(lon12)

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

515 lam12 = radians(lon12)

516 if lon12 > _90_0:

517 slam12, clam12 = _sincos2d(lon12s)

518 clam12 = -clam12

519 else:

520 slam12, clam12 = _sincos2(lam12)

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

522 lat1 = _around(_fix90(lat1))

523 lat2 = _around(_fix90(lat2))

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

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

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

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

528 if swap_:

529 lat1, lat2 = lat2, lat1

530 lon_ = not lon_

531 if _signBit(lat1):

532 lat_ = False # note, False

533 else: # make lat1 <= -0

534 lat_ = True # note, True

535 lat1, lat2 = -lat1, -lat2

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

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

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

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

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

541 # this enforces some symmetries in the results returned.

542

543 # Initialize for the meridian. No longitude calculation is

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

545 sbet1, cbet1 = self._sinf1cos2d(lat1)

546 sbet2, cbet2 = self._sinf1cos2d(lat2)

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

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

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

550 # in assigning calp2 in _Lambda6. Sometimes these quantities

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

552 # example where is is necessary is the inverse problem

553 # 48.522876735459 0 -48.52287673545898293 179.599720456223079643

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

555 if cbet1 < -sbet1:

556 if cbet2 == cbet1:

557 sbet2 = copysign(sbet1, sbet2)

558 elif fabs(sbet2) == -sbet1:

559 cbet2 = cbet1

560

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

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

563

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

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

566 # Endpoints are on a single full meridian,

567 # so the geodesic might lie on a meridian.

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

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

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

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

572 # sig12 = sig2 - sig1

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

574 s12x, m12x, _, \

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

576 # Add the check for sig12 since zero length geodesics

577 # might yield m12 < 0. Test case was

578 # echo 20.001 0 20.001 0 | GeodSolve -i

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

580 # geodesic which is not a shortest path.

581 if m12x >= 0 or sig12 < _1_0:

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

583 # Prevent negative s12 or m12 from geographiclib 1.52

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

585 sig12 = m12x = s12x = _0_0

586 else:

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

588 _meridian = False

589 C = 1

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

591 # _meridian = True

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

593

594 if _meridian:

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

596 if _b: # Geodesic runs along equator

597 calp1 = calp2 = _0_0

598 salp1 = salp2 = _1_0

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

600 somg12, comg12 = _sincos2(sig12)

601 m12x = self.b * somg12

602 s12x = self.a * lam12

603 M12 = M21 = comg12

604 a12 = lon12 / self.f1

605 C = 2

606 else:

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

608 # meridian and geodesic is neither meridional or equatorial.

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

610 # Figure a starting point for Newton's method

611 sig12, salp1, calp1, \

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

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

614 # pre-compute the constant _Lambda6 term, once

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

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

617 ((sbet1 + sbet2) * (sbet1 - sbet2))))

618 sig12, salp1, calp1, \

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

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

621 if (outmask & Cs.AREA):

622 # omg12 = lam12 - domg12

623 s, c = _sincos2(domg12)

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

625 C = 3 # Newton

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

627 C = 4 # Short lines

628 s, c = _sincos2(sig12 / dnm)

629 m12x = dnm**2 * s

630 s12x = dnm * sig12

631 M12 = M21 = c

632 if (outmask & Cs.AREA):

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

634

635 else: # _meridian is False

636 somg12 = comg12 = NAN

637

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

639

640 if (outmask & Cs.DISTANCE):

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

642

643 if (outmask & Cs.REDUCEDLENGTH):

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

645

646 if (outmask & Cs.GEODESICSCALE):

647 if swap_:

648 M12, M21 = M21, M12

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

650 M21=unsigned0(M21))

651

652 if (outmask & Cs.AREA):

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

654 salp2, calp2,

655 somg12, comg12, p)

656 if _xor(swap_, lat_, lon_):

657 S12 = -S12

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

659

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

661 if swap_:

662 salp1, salp2 = salp2, salp1

663 calp1, calp2 = calp2, calp1

664 if _xor(swap_, lon_):

665 salp1, salp2 = -salp1, -salp2

666 if _xor(swap_, lat_):

667 calp1, calp2 = -calp1, -calp2

668

669 if (outmask & Cs.AZIMUTH):

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

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

672 if (outmask & Cs._SALPs_CALPs):

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

674 salp2=salp2, calp2=calp2)

675

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

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

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

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

680 c2=E.c2, c2x=self.c2x,

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

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

683 p.update(r) # r overrides p

684 r = p.toGDict()

685 return self._iter2tion(r, p)

686

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

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

689

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

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

692 '''

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

694 return r.toDirect9Tuple()

695

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

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

698

699 @return: A L{GeodesicLineExact} instance.

700 '''

701 azi1 = _norm180(azi1)

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

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

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

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

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

707

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

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

710

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

712 m12, M12, M21, S12)}.

713 '''

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

715 return r.toInverse10Tuple()

716

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

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

719

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

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

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

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

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

725 the quantities to be returned.

726

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

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

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

730

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

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

733

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

735

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

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

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

739 '''

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

741

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

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

744

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

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

747 '''

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

749 # and .HeightIDWkarney._distances

750 if wrap:

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

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

753

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

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

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

757

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

759 '''

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

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

762 iteration=r.iteration)

763

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

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

766

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

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

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

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

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

772 the capabilities the L{GeodesicLineExact} instance

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

774 returned by calls to L{GeodesicLineExact.Position}

775 and L{GeodesicLineExact.ArcPosition}.

776

777 @return: A L{GeodesicLineExact} instance.

778

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

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

781

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

783

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

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

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

787 '''

788 Cs = Caps

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

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

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

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

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

794

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

796 salp2, calp2,

797 somg12, comg12, p):

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

799

800 @return: Area C{S12}.

801 '''

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

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

804 A4 = calp0 * salp0

805 if A4:

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

807 k2 = calp0**2 * self.ep2

808 C4a = self._C4f_k2(k2)

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

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

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

812 A4 *= self._e2a2

813 S12 = A4 * (B42 - B41)

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

815 A4 = B41 = B42 = k2 = S12 = _0_0

816

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

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

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

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

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

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

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

824 dbet1 = p.cbet1 + _1_0

825 dbet2 = p.cbet2 + _1_0

826 domg12 = comg12 + _1_0

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

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

829 alp12 = _2_0 * atan2(salp12, calp12)

830 else:

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

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

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

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

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

836 # Following ensures the correct behavior.

837 if salp12 == 0 and calp12 < 0:

838 alp12 = _copysign(PI, calp1)

839 else:

840 alp12 = atan2(salp12, calp12)

841

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

843 return S12 + self.c2x * alp12

844

845 def _InverseStart6(self, lam12, p):

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

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

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

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

850

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

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

853 '''

854 sig12 = None # use Newton

855 salp1 = calp1 = salp2 = calp2 = dnm = NAN

856

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

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

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

860 if shortline:

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

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

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

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

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

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

867 else:

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

869

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

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

872

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

874 s = somg12**2 / c

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

876 salp1 = p.cbet2 * somg12

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

878

879 ssig12 = _hypot(salp1, calp1)

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

881

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

883 t = c if comg12 < 0 else s

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

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

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

887

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

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

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

891

892 else:

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

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

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

896 f = self.f

897 if f < 0: # PYCHOK no cover

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

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

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

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

902 Caps.REDUCEDLENGTH, p)

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

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

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

906 y = lam12x / sca

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

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

909 x = lam12x / sca # dlon

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

911

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

913 if f < 0: # PYCHOK no cover

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

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

916 else:

917 salp1 = min( _1_0, -x)

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

919 else:

920 # Estimate alp1, by solving the astroid problem.

921 #

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

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

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

925 #

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

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

928 # number of Newton iterations for astroid cases from 2.24

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

930 # number of iterations are as follows:

931 #

932 # change percent

933 # 1 5

934 # 0 78

935 # -1 16

936 # -2 0.6

937 # -3 0.04

938 # -4 0.002

939 #

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

941 # estimating alp1 directly, n = number of iterations

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

943 #

944 # iter m n

945 # 0 148 186

946 # 1 13046 13845

947 # 2 93315 102225

948 # 3 36189 32341

949 # 4 5396 7

950 # 5 455 1

951 # 6 56 0

952 #

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

954 k = _Astroid(x, y)

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

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

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

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

959 salp1 = p.cbet2 * s

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

961

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

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

964

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

966

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

968 '''(INTERNAL) Helper.

969

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

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

972 '''

973 eF = self._eF

974 f1 = self.f1

975

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

977 # Break degeneracy of equatorial line

978 calp1 = -_TINY

979

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

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

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

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

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

985 somg1 = salp0 * p.sbet1

986 comg1 = calp1 * p.cbet1

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

988 # Without normalization we have schi1 = somg1

989 cchi1 = f1 * p.dn1 * comg1

990

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

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

993 # yield singularities in the Newton iteration.

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

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

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

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

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

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

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

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

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

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

1004 somg2 = salp0 * p.sbet2

1005 comg2 = calp2 * p.cbet2

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

1007 # without normalization we have schi2 = somg2

1008 cchi2 = f1 * p.dn2 * comg2

1009

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

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

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

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

1014

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

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

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

1018

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

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

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

1022 # eta = chi12 - lam12

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

1024 # domg12 = chi12 - omg12 - deta12

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

1026

1027 dlam12 = NAN # dv > 0 in ._Newton6

1028 if diffp:

1029 d = calp2 * p.cbet2

1030 if d:

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

1032 dlam12 *= f1 / d

1033 elif p.sbet1:

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

1035

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

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

1038

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

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

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

1042 coefficient of secular term in expression for reduced

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

1044

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

1046 '''

1047 s12b = m12b = m0 = M12 = M21 = NAN

1048

1049 Cs = Caps

1050 eF = self._eF

1051

1052 # outmask &= Cs._OUT_MASK

1053 if (outmask & Cs.DISTANCE):

1054 # Missing a factor of self.b

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

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

1057

1058 if (outmask & Cs._REDUCEDLENGTH_GEODESICSCALE):

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

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

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

1062 if (outmask & Cs.REDUCEDLENGTH):

1063 m0 = m0x

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

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

1066 # accurate cancellation for coincident points.

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

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

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

1070 if (outmask & Cs.GEODESICSCALE):

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

1072 p.csig1 * p.csig2

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

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

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

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

1077

1078 return s12b, m12b, m0, M12, M21

1079

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

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

1082 on a single geodesic.

1083

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

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

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

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

1088 the capabilities the L{GeodesicLineExact} instance

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

1090 returnedby calls to L{GeodesicLineExact.Position}

1091 and L{GeodesicLineExact.ArcPosition}.

1092

1093 @return: A L{GeodesicLineExact} instance.

1094

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

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

1097 the limit C{ε → 0+}.

1098

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

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

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

1102 '''

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

1104

1105 @Property_RO

1106 def n(self):

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

1108 '''

1109 return self.ellipsoid.n

1110

1111 @Property_RO

1112 def _n_0_1(self):

1113 '''(INTERNAL) Cached once.

1114 '''

1115 return fabs(self.n) > _0_1

1116

1117 @Property_RO

1118 def _n6PI(self):

1119 '''(INTERNAL) Cached once.

1120 '''

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

1122

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

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

1125

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

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

1128 '''

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

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

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

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

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

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

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

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

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

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

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

1140 salp1a = salp1b = _TINY

1141 calp1a, calp1b = _1_0, _N_1_0

1142 MAXIT1, TOL0 = _MAXIT1, _TOL0

1143 HALF, TOLb = _0_5, _TOLb

1144 tripb, TOLv = False, TOL0

1145 for i in range(_MAXIT2):

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

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

1148 # checking Inverse problem by Direct).

1149 #

1150 # max iterations

1151 # log2(b/a) error mean sd

1152 # -7 387 5.33 3.68

1153 # -6 345 5.19 3.43

1154 # -5 269 5.00 3.05

1155 # -4 210 4.76 2.44

1156 # -3 115 4.55 1.87

1157 # -2 69 4.35 1.38

1158 # -1 36 4.05 1.03

1159 # 0 15 0.01 0.13

1160 # 1 25 5.10 1.53

1161 # 2 96 5.61 2.09

1162 # 3 318 6.02 2.74

1163 # 4 985 6.24 3.22

1164 # 5 2352 6.32 3.44

1165 # 6 6008 6.30 3.45

1166 # 7 19024 6.19 3.30

1167 v, sig12, salp2, calp2, \

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

1169

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

1171 # reversed test to allow escape with NaNs

1172 if tripb or fabs(v) < TOLv:

1173 break

1174 # update bracketing values

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

1176 salp1b, calp1b = salp1, calp1

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

1178 salp1a, calp1a = salp1, calp1

1179

1180 if i < MAXIT1 and dv > 0:

1181 dalp1 = -v / dv

1182 if fabs(dalp1) < PI:

1183 s, c = _sincos2(dalp1)

1184 # nalp1 = alp1 + dalp1

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

1186 if s > 0:

1187 salp1, calp1 = _norm2(s, c)

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

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

1190 # based on epsilon instead of sqrt(epsilon)

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

1192 continue

1193

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

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

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

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

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

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

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

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

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

1203 (calp1a + calp1b) * HALF)

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

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

1206 TOLv = TOL0

1207

1208 else:

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

1210

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

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

1213

1214 Polygon = Area # for C{geographiclib} compatibility

1215

1216 def _sinf1cos2d(self, lat):

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

1218 '''

1219 sbet, cbet = _sincos2d(lat)

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

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

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

1223 return sbet, max(_TINY, cbet)

1224

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

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

1227

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

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

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

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

1232

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

1234 '''

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

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

1237

1238

1239 class GeodesicLineExact(_GeodesicLineExact):

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

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

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

1243 geographiclib/geographiclib-python>}.

1244 '''

1245

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

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

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

1249

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

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

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

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

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

1255 the capabilities the L{GeodesicLineExact} instance

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

1257 returned by calls to L{GeodesicLineExact.Position}

1258 and L{GeodesicLineExact.ArcPosition}.

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

1260

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

1262 '''

1263 _xinstanceof(GeodesicExact, geodesic=geodesic)

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

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

1266# _update_all(geodesic)

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

1268

1269

1270 def _Astroid(x, y):

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

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

1273 '''

1274 p = x**2

1275 q = y**2

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

1277 if r > 0 or q:

1278 # avoid possible division by zero when r = 0

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

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

1281 if r:

1282 r = r / _6_0 # /= chokes PyChecker

1283 r3 = r**3

1284 T3 = r3 + S

1285 # discriminant of the quadratic equation for T3 is

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

1287 d = (r3 + T3) * S

1288 if d < 0:

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

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

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

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

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

1294 else:

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

1296 # minimize loss of precision due to cancellation.

1297 if d:

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

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

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

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

1302 u += r**2 / u

1303 u += r

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

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

1306 else:

1307 u = _0_0

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

1309 # avoid loss of accuracy when u < 0

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

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

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

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

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

1315

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

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

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

1319 k = _0_0

1320

1321 return k

1322

1323

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

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

1326 '''

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

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

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

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

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

1332 n = _xnC4(nC4=nC4)

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

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

1335 return _coeffs

1336

1337

1338__all__ += _ALL_DOCS(GeodesicExact, GeodesicLineExact)

1339

1340# **) MIT License

1341#

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

1343#

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

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

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

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

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

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

1350#

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

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

1353#

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

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

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

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

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

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

1360# OTHER DEALINGS IN THE SOFTWARE.