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# - lambda = longitude

25# - beta = latitude on auxiliary sphere

26# - omega = longitude on auxiliary sphere

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 _copysign, _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 _earth_datum, _WGS84, _EWGS84

45# from pygeodesy.ellipsoids import _EWGS84 # from .datums

46 from pygeodesy.errors import GeodesicError, _xkwds_pop2

47 from pygeodesy.fmath import hypot as _hypot, Fmt

48 from pygeodesy.fsums import fsumf_, fsum1f_

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

50 _sincos12, _sin1cos2, _sinf1cos2d, \

51 _TINY, _xnC4

52 from pygeodesy.geodesicx.gxline import _GeodesicLineExact, _update_glXs

53 from pygeodesy.interns import NN, _DOT_, _UNDER_

54 from pygeodesy.karney import GDict, _around, _atan2d, Caps, _cbrt, _diff182, \

55 _fix90, _K_2_0, _norm2, _norm180, _polynomial, \

56 _signBit, _sincos2, _sincos2d, _sincos2de, _unsigned2

57 from pygeodesy.lazily import _ALL_DOCS, _ALL_MODS as _MODS

58 from pygeodesy.namedTuples import Destination3Tuple, Distance3Tuple

59 from pygeodesy.props import deprecated_Property, Property, Property_RO, property_RO

60# from pygeodesy.streprs import Fmt # from .fmath

61 from pygeodesy.utily import atan2d as _atan2d_reverse, _unrollon, _Wrap, wrap360

62

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

64

65__all__ = ()

66__version__ = '24.06.24'

67

68_MAXIT1 = 20

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

70

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

72# case 52.784459512564 0 -52.784459512563990912 179.634407464943777557

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

74_TOL0 = EPS

75_TOL1 = _TOL0 * -200 # negative

76_TOL2 = _EPSqrt # == sqrt(_TOL0)

77_TOL3 = _TOL2 * _0_1

78_TOLb = _TOL2 * _TOL0 # Check on bisection interval

79_THR1 = _TOL2 * _1000_0 + _1_0

80

81_TINY3 = _TINY * _3_0

82_TOL08 = _TOL0 * _8_0

83_TOL016 = _TOL0 * _16_0

84

85

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

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

88 '''

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

90

91

92 def _eTOL2(f):

93 # Using the auxiliary sphere solution with dnm computed at

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

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

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

97

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

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

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

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

102

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

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

105 # nearly spherical case.

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

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

108

109

110 class _PDict(GDict):

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

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

113 '''

114 def set_sigs(self, ssig1, csig1, ssig2, csig2):

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

116 '''

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

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

119

120 def toGDict(self): # PYCHOK no cover

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

122 '''

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

124 return GDict(rest)

125

126 return _rest(**self)

127

128

129 class GeodesicExact(_GeodesicBase):

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

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

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

133 geographiclib/geographiclib-python>}.

134 '''

135 _datum = _WGS84

136 _nC4 = 30 # default C4order

137

138 def __init__(self, a_ellipsoid=_EWGS84, f=None, C4order=None, **name_C4Order): # 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 C4order: Optional series expansion order (C{int}), see property

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

148 @kwarg name_C4Order: Optional C{B{name}=NN} (C{str}) and the DEPRECATED

149 keyword argument C{C4Order}, use B{C{C4order}} instead.

150

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

152 '''

153 if name_C4Order:

154 C4order, name = _xkwds_pop2(name_C4Order, C4Order=C4order)

155 if name:

156 self.name = name

157 else:

158 name = {} # name_C4Order

159

160 _earth_datum(self, a_ellipsoid, f=f, **name)

161 if C4order: # XXX private copy, always?

162 self.C4order = C4order

163

164 @Property_RO

165 def a(self):

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

167 '''

168 return self.ellipsoid.a

169

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

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

172

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

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

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

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

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

178 the quantities to be returned.

179

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

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

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

183

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

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

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

187 '''

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

189

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

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

192

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

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

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

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

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

198 the capabilities the L{GeodesicLineExact} instance

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

200 returned by calls to L{GeodesicLineExact.Position}

201 and L{GeodesicLineExact.ArcPosition}.

202 @kwarg name: Optional C{B{name}=NN} (C{str}).

203

204 @return: A L{GeodesicLineExact} instance.

205

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

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

208

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

210

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

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

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

214 '''

215 return self._GenDirectLine(lat1, lon1, azi1, True, a12, caps, **name)

216

217 def Area(self, polyline=False, **name):

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

219 perimeter of a polygon.

220

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

222 area and perimeter (C{bool}).

223 @kwarg name: Optional C{B{name}=NN} (C{str}).

224

225 @return: A L{GeodesicAreaExact} instance.

226

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

228 to the returned L{GeodesicAreaExact} instance.

229 '''

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

231 name=self._name__(name))

232 if self.debug:

233 gaX.verbose = True

234 return gaX

235

236 @Property_RO

237 def b(self):

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

239 '''

240 return self.ellipsoid.b

241

242 @Property_RO

243 def c2x(self):

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

245 '''

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

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

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

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

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

251 return self.ellipsoid.c2x

252

253 c2 = c2x # in this particular case

254

255 def C4f(self, eps):

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

257

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

259

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

261 '''

262 def _c4(nC4, C4x):

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

264 _p = _polynomial

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

266 j = i + r

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

268 x *= e

269 i = j

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

271

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

273

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

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

276 '''

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

278

279 @Property

280 def C4order(self):

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

282 '''

283 return self._nC4

284

285 @C4order.setter # PYCHOK .setter!

286 def C4order(self, order):

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

288

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

290 '''

291 _xnC4(C4order=order)

292 if self._nC4 != order:

293 GeodesicExact._C4x._update(self)

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

295 self._nC4 = order

296

297 @deprecated_Property

298 def C4Order(self):

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

300 '''

301 return self.C4order

302

303 @C4Order.setter # PYCHOK .setter!

304 def C4Order(self, order):

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

306 '''

307 _xnC4(C4Order=order)

308 self.C4order = order

309

310 @Property_RO

311 def _C4x(self):

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

313

314 @see: Property L{C4order}.

315 '''

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

317 def _C4(nC4):

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

319 _p = _polynomial

320 for r in range(nC4 + 1, 1, -1): # _reverange

321 for j in range(1, r):

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

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

324 i = j + 1

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

326

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

328

329 @property_RO

330 def datum(self):

331 '''Get the datum (C{Datum}).

332 '''

333 return self._datum

334

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

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

337

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

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

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

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

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

343 the quantities to be returned.

344

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

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

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

348

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

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

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

352 '''

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

354

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

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

357 (final bearing) in C{degrees}.

358

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

360 '''

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

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

363

364 def _DirectLine(self, ll1, azi12, s12=0, **caps_name):

365 '''(INTERNAL) Short-cut version.

366 '''

367 return self.DirectLine(ll1.lat, ll1.lon, azi12, s12, **caps_name)

368

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

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

371

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

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

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

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

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

377 the capabilities the L{GeodesicLineExact} instance

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

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

380 @kwarg name: Optional C{B{name}=NN} (C{str}).

381

382 @return: A L{GeodesicLineExact} instance.

383

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

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

386

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

388

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

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

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

392 '''

393 return self._GenDirectLine(lat1, lon1, azi1, False, s12, caps, **name)

394

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

396 '''(INTERNAL) Helper.

397 '''

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

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

400 else:

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

402 return dn

403

404 @Property_RO

405 def e2(self):

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

407 '''

408 return self.ellipsoid.e2

409

410 @Property_RO

411 def _e2a2(self):

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

413 '''

414 return self.e2 * self.ellipsoid.a2

415

416 @Property_RO

417 def _e2_f1(self):

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

419 '''

420 return self.e2 / self.f1

421

422 @Property_RO

423 def _eF(self):

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

425 '''

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

427

428 def _eF_reset_cHe2_f1(self, x, y):

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

430 '''

431 self._eF_reset_k2(x)

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

433

434 def _eF_reset_k2(self, x):

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

436 '''

437 ep2 = self.ep2

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

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

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

441 return k2

442

443 @Property_RO

444 def ellipsoid(self):

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

446 '''

447 return self.datum.ellipsoid

448

449 @Property_RO

450 def ep2(self):

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

452 '''

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

454

455 e22 = ep2 # for ellipsoid compatibility

456

457 @Property_RO

458 def _eTOL2(self):

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

460 '''

461 return _eTOL2(self.f)

462

463 @Property_RO

464 def flattening(self):

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

466 '''

467 return self.ellipsoid.f

468

469 f = flattening

470

471 @Property_RO

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

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

474 '''

475 return self.ellipsoid.f1

476

477 @Property_RO

478 def _f180(self):

479 '''(INTERNAL) Cached/memoized.

480 '''

481 return self.f * _180_0

482

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

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

485

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

487 '''

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

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

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

491

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

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

494

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

496 '''

497 Cs = Caps

498 if self._debug: # PYCHOK no cover

499 outmask |= Cs._DEBUG_INVERSE & self._debug

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

501 # compute longitude difference carefully (with _diff182):

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

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

504 lon12, lon12s = _diff182(lon1, lon2)

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

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

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

508 else:

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

510 if _K_2_0: # GeographicLib 2.0

511 # make longitude difference positive

512 lon12, lon_ = _unsigned2(lon12)

513 if lon_:

514 lon12s = -lon12s

515 lam12 = radians(lon12)

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

517 slam12, clam12 = _sincos2de(lon12, lon12s)

518 # supplementary longitude difference

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

520 else: # GeographicLib 1.52

521 # make longitude difference positive and if very close

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

523 if lon12 < 0: # _signBit(lon12)

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

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

526 else:

527 lon_, lon12 = False, _around(lon12)

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

529 lam12 = radians(lon12)

530 if lon12 > _90_0:

531 slam12, clam12 = _sincos2d(lon12s)

532 clam12 = -clam12

533 else:

534 slam12, clam12 = _sincos2(lam12)

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

536 lat1 = _around(_fix90(lat1))

537 lat2 = _around(_fix90(lat2))

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

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

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

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

542 if swap_:

543 lat1, lat2 = lat2, lat1

544 lon_ = not lon_

545 if _signBit(lat1):

546 lat_ = False # note, False

547 else: # make lat1 <= -0

548 lat_ = True # note, True

549 lat1, lat2 = -lat1, -lat2

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

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

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

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

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

555 # this enforces some symmetries in the results returned.

556

557 # Initialize for the meridian. No longitude calculation is done in

558 # this case to let the parameter default to 0.

559 sbet1, cbet1 = _sinf1cos2d(lat1, self.f1)

560 sbet2, cbet2 = _sinf1cos2d(lat2, self.f1)

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

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

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

564 # in assigning calp2 in _Lambda6. Sometimes these quantities

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

566 # example where is is necessary is the inverse problem

567 # 48.522876735459 0 -48.52287673545898293 179.599720456223079643

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

569 if cbet1 < -sbet1:

570 if cbet2 == cbet1:

571 sbet2 = copysign(sbet1, sbet2)

572 elif fabs(sbet2) == -sbet1:

573 cbet2 = cbet1

574

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

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

577

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

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

580 # Endpoints are on a single full meridian,

581 # so the geodesic might lie on a meridian.

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

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

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

585 p.set_sigs(sbet1, calp1 * cbet1, sbet2, calp2 * cbet2)

586 # sig12 = sig2 - sig1

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

588 s12x, m12x, _, \

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

590 # Add the check for sig12 since zero length geodesics

591 # might yield m12 < 0. Test case was

592 # echo 20.001 0 20.001 0 | GeodSolve -i

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

594 # geodesic which is not a shortest path.

595 if m12x >= 0 or sig12 < _1_0:

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

597 # Prevent negative s12 or m12 from geographiclib 1.52

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

599 sig12 = m12x = s12x = _0_0

600 else:

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

602 _meridian = False

603 C = 1

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

605 # _meridian = True

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

607

608 if _meridian:

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

610 if _b: # Geodesic runs along equator

611 calp1 = calp2 = _0_0

612 salp1 = salp2 = _1_0

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

614 somg12, comg12 = _sincos2(sig12)

615 m12x = self.b * somg12

616 s12x = self.a * lam12

617 M12 = M21 = comg12

618 a12 = lon12 / self.f1

619 C = 2

620 else:

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

622 # meridian and geodesic is neither meridional or equatorial.

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

624 # Figure a starting point for Newton's method

625 sig12, salp1, calp1, \

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

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

628 # pre-compute the constant _Lambda6 term, once

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

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

631 ((sbet1 + sbet2) * (sbet1 - sbet2))))

632 sig12, salp1, calp1, \

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

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

635 if (outmask & Cs.AREA):

636 # omg12 = lam12 - domg12

637 s, c = _sincos2(domg12)

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

639 C = 3 # Newton

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

641 C = 4 # Short lines

642 s, c = _sincos2(sig12 / dnm)

643 m12x = dnm**2 * s

644 s12x = dnm * sig12

645 M12 = M21 = c

646 if (outmask & Cs.AREA):

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

648

649 else: # _meridian is False

650 somg12 = comg12 = NAN

651

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

653

654 if (outmask & Cs.DISTANCE):

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

656

657 if (outmask & Cs.REDUCEDLENGTH):

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

659

660 if (outmask & Cs.GEODESICSCALE):

661 if swap_:

662 M12, M21 = M21, M12

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

664 M21=unsigned0(M21))

665

666 if (outmask & Cs.AREA):

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

668 salp2, calp2,

669 somg12, comg12, p)

670 if _xor(swap_, lat_, lon_):

671 S12 = -S12

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

673

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

675 if swap_:

676 salp1, salp2 = salp2, salp1

677 calp1, calp2 = calp2, calp1

678 if _xor(swap_, lon_):

679 salp1, salp2 = -salp1, -salp2

680 if _xor(swap_, lat_):

681 calp1, calp2 = -calp1, -calp2

682

683 if (outmask & Cs.AZIMUTH):

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

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

686 if (outmask & Cs._SALPs_CALPs):

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

688 salp2=salp2, calp2=calp2)

689

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

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

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

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

694 c2=E.c2, c2x=self.c2x,

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

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

697 p.update(r) # r overrides p

698 r = p.toGDict()

699 return self._iter2tion(r, **p)

700

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

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

703

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

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

706 '''

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

708 return r.toDirect9Tuple()

709

710 def _GenDirectLine(self, lat1, lon1, azi1, arcmode, s12_a12, caps, **name):

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

712

713 @return: A L{GeodesicLineExact} instance.

714 '''

715 azi1 = _norm180(azi1)

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

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

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

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

720 self._debug, s, c, **name)._GenSet(arcmode, s12_a12)

721

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

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

724

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

726 m12, M12, M21, S12)}.

727 '''

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

729 return r.toInverse10Tuple()

730

731 def _Inverse(self, ll1, ll2, wrap, **outmask):

732 '''(INTERNAL) Short-cut version, see .base.ellipsoidalDI.intersecant2.

733 '''

734 if wrap:

735 ll2 = _unrollon(ll1, _Wrap.point(ll2))

736 return self.Inverse(ll1.lat, ll1.lon, ll2.lat, ll2.lon, **outmask)

737

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

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

740

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

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

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

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

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

746 the quantities to be returned.

747

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

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

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

751

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

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

754

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

756

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

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

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

760 '''

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

762

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

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

765

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

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

768 '''

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

770 # and .HeightIDWkarney._distances

771 if wrap:

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

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

774

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

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

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

778

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

780 '''

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

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

783 iteration=r.iteration)

784

785 def _InverseLine(self, ll1, ll2, wrap, **caps_name):

786 '''(INTERNAL) Short-cut version.

787 '''

788 if wrap:

789 ll2 = _unrollon(ll1, _Wrap.point(ll2))

790 return self.InverseLine(ll1.lat, ll1.lon, ll2.lat, ll2.lon, **caps_name)

791

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

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

794

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

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

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

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

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

800 the capabilities the L{GeodesicLineExact} instance

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

802 returned by calls to L{GeodesicLineExact.Position}

803 and L{GeodesicLineExact.ArcPosition}.

804 @kwarg name: Optional C{B{name}=NN} (C{str}).

805

806 @return: A L{GeodesicLineExact} instance.

807

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

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

810

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

812

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

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

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

816 '''

817 Cs = Caps

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

819 C = (caps | Cs.DISTANCE) if (caps & (Cs.DISTANCE_IN & Cs._OUT_MASK)) else caps

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

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

822 self._debug, r.salp1, r.calp1, **name)._GenSet(True, r.a12)

823

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

825 salp2, calp2,

826 somg12, comg12, p):

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

828

829 @return: Area C{S12}.

830 '''

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

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

833 A4 = calp0 * salp0

834 if A4:

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

836 k2 = calp0**2 * self.ep2

837 C4a = self._C4f_k2(k2)

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

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

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

841 A4 *= self._e2a2

842 S12 = A4 * (B42 - B41)

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

844 A4 = B41 = B42 = k2 = S12 = _0_0

845

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

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

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

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

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

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

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

853 dbet1 = p.cbet1 + _1_0

854 dbet2 = p.cbet2 + _1_0

855 domg12 = comg12 + _1_0

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

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

858 alp12 = atan2(salp12, calp12) * _2_0

859 else:

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

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

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

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

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

865 # Following ensures the correct behavior.

866 if salp12 == 0 and calp12 < 0:

867 alp12 = _copysign(PI, calp1)

868 else:

869 alp12 = atan2(salp12, calp12)

870

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

872 return S12 + self.c2x * alp12

873

874 def _InverseStart6(self, lam12, p):

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

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

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

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

879

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

881 and C{p.set_sigs} updated for Newton, C{sig12=None}.

882 '''

883 sig12 = None # use Newton

884 salp1 = calp1 = salp2 = calp2 = dnm = NAN

885

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

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

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

889 if shortline:

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

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

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

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

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

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

896 else:

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

898

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

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

901

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

903 s = somg12**2 / c

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

905 salp1 = p.cbet2 * somg12

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

907

908 ssig12 = _hypot(salp1, calp1)

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

910

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

912 t = c if comg12 < 0 else s

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

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

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

916

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

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

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

920

921 else:

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

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

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

925 f = self.f

926 if f < 0: # PYCHOK no cover

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

928 p.set_sigs(p.sbet1, -p.cbet1, p.sbet2, p.cbet2)

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

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

931 Caps.REDUCEDLENGTH, p)

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

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

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

935 y = lam12x / sca

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

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

938 x = lam12x / sca # dlon

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

940

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

942 if f < 0: # PYCHOK no cover

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

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

945 else:

946 salp1 = min( _1_0, -x)

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

948 else:

949 # Estimate alp1, by solving the astroid problem.

950 #

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

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

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

954 #

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

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

957 # number of Newton iterations for astroid cases from 2.24

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

959 # number of iterations are as follows:

960 #

961 # change percent

962 # 1 5

963 # 0 78

964 # -1 16

965 # -2 0.6

966 # -3 0.04

967 # -4 0.002

968 #

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

970 # estimating alp1 directly, n = number of iterations

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

972 #

973 # iter m n

974 # 0 148 186

975 # 1 13046 13845

976 # 2 93315 102225

977 # 3 36189 32341

978 # 4 5396 7

979 # 5 455 1

980 # 6 56 0

981 #

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

983 k = _Astroid(x, y)

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

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

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

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

988 salp1 = p.cbet2 * s

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

990

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

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

993

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

995

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

997 '''(INTERNAL) Helper.

998

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

1000 dlam12} and C{p.set_sigs} updated.

1001 '''

1002 eF = self._eF

1003 f1 = self.f1

1004

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

1006 # Break degeneracy of equatorial line

1007 calp1 = -_TINY

1008

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

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

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

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

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

1014 somg1 = salp0 * p.sbet1

1015 comg1 = calp1 * p.cbet1

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

1017 # Without normalization we have schi1 = somg1

1018 cchi1 = f1 * p.dn1 * comg1

1019

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

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

1022 # yield singularities in the Newton iteration.

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

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

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

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

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

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

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

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

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

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

1033 somg2 = salp0 * p.sbet2

1034 comg2 = calp2 * p.cbet2

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

1036 # without normalization we have schi2 = somg2

1037 cchi2 = f1 * p.dn2 * comg2

1038

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

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

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

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

1043

1044 p.set_sigs(ssig1, csig1, ssig2, csig2)

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

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

1047

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

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

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

1051 # eta = chi12 - lam12

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

1053 # domg12 = chi12 - omg12 - deta12

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

1055

1056 dlam12 = NAN # dv > 0 in ._Newton6

1057 if diffp:

1058 d = calp2 * p.cbet2

1059 if d:

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

1061 dlam12 *= f1 / d

1062 elif p.sbet1:

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

1064

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

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

1067

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

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

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

1071 coefficient of secular term in expression for reduced

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

1073

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

1075 '''

1076 s12b = m12b = m0 = M12 = M21 = NAN

1077

1078 Cs = Caps

1079 eF = self._eF

1080

1081 # outmask &= Cs._OUT_MASK

1082 if (outmask & Cs.DISTANCE):

1083 # Missing a factor of self.b

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

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

1086

1087 if (outmask & Cs._REDUCEDLENGTH_GEODESICSCALE):

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

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

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

1091 if (outmask & Cs.REDUCEDLENGTH):

1092 m0 = m0x

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

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

1095 # accurate cancellation for coincident points.

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

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

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

1099 if (outmask & Cs.GEODESICSCALE):

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

1101 p.csig1 * p.csig2

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

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

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

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

1106

1107 return s12b, m12b, m0, M12, M21

1108

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

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

1111 on a single geodesic.

1112

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

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

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

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

1117 the capabilities the L{GeodesicLineExact} instance

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

1119 returnedby calls to L{GeodesicLineExact.Position}

1120 and L{GeodesicLineExact.ArcPosition}.

1121 @kwarg name: Optional C{B{name}=NN} (C{str}).

1122

1123 @return: A L{GeodesicLineExact} instance.

1124

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

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

1127 the limit C{ε → 0+}.

1128

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

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

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

1132 '''

1133 return _GeodesicLineExact(self, lat1, lon1, azi1, caps, self._debug, **name)

1134

1135 @Property_RO

1136 def n(self):

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

1138 '''

1139 return self.ellipsoid.n

1140

1141 @Property_RO

1142 def _n_0_1(self):

1143 '''(INTERNAL) Cached once.

1144 '''

1145 return fabs(self.n) > _0_1

1146

1147 @Property_RO

1148 def _n6PI(self):

1149 '''(INTERNAL) Cached once.

1150 '''

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

1152

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

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

1155

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

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

1158 '''

1159 _abs = fabs

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

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

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

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

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

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

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

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

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

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

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

1171 salp1a = salp1b = _TINY

1172 calp1a, calp1b = _1_0, _N_1_0

1173 MAXIT1, TOL0 = _MAXIT1, _TOL0

1174 HALF, TOLb = _0_5, _TOLb

1175 tripb, TOLv = False, TOL0

1176 for i in range(_MAXIT2):

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

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

1179 # checking Inverse problem by Direct).

1180 #

1181 # max iterations

1182 # log2(b/a) error mean sd

1183 # -7 387 5.33 3.68

1184 # -6 345 5.19 3.43

1185 # -5 269 5.00 3.05

1186 # -4 210 4.76 2.44

1187 # -3 115 4.55 1.87

1188 # -2 69 4.35 1.38

1189 # -1 36 4.05 1.03

1190 # 0 15 0.01 0.13

1191 # 1 25 5.10 1.53

1192 # 2 96 5.61 2.09

1193 # 3 318 6.02 2.74

1194 # 4 985 6.24 3.22

1195 # 5 2352 6.32 3.44

1196 # 6 6008 6.30 3.45

1197 # 7 19024 6.19 3.30

1198 v, sig12, salp2, calp2, \

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

1200

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

1202 # reversed test to allow escape with NaNs

1203 if tripb or _abs(v) < TOLv:

1204 break

1205 # update bracketing values

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

1207 salp1b, calp1b = salp1, calp1

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

1209 salp1a, calp1a = salp1, calp1

1210

1211 if i < MAXIT1 and dv > 0:

1212 dalp1 = -v / dv

1213 if _abs(dalp1) < PI:

1214 s, c = _sincos2(dalp1)

1215 # nalp1 = alp1 + dalp1

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

1217 if s > 0:

1218 salp1, calp1 = _norm2(s, c)

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

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

1221 # based on epsilon instead of sqrt(epsilon)

1222 TOLv = TOL0 if _abs(v) > _TOL016 else _TOL08

1223 continue

1224 TOLv = TOL0

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

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

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

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

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

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

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

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

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

1234 (calp1a + calp1b) * HALF)

1235 tripb = fsum1f_(calp1a, -calp1, _abs(salp1a - salp1)) < TOLb or \

1236 fsum1f_(calp1b, -calp1, _abs(salp1b - salp1)) < TOLb

1237 else:

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

1239

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

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

1242

1243 Polygon = Area # for C{geographiclib} compatibility

1244

1245 def toStr(self, **prec_sep_name): # PYCHOK signature

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

1247

1248 @see: L{Ellipsoid.toStr<pygeodesy.ellipsoids.Ellipsoid.toStr>}

1249 for further details.

1250

1251 @return: C{GeodesicExact} (C{str}).

1252 '''

1253 return self._instr(props=(GeodesicExact.ellipsoid,),

1254 C4order=self.C4order, **prec_sep_name)

1255

1256

1257 class GeodesicLineExact(_GeodesicLineExact):

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

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

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

1261 geographiclib/geographiclib-python>}.

1262 '''

1263

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

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

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

1267

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

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

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

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

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

1273 the capabilities the L{GeodesicLineExact} instance

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

1275 returned by calls to L{GeodesicLineExact.Position}

1276 and L{GeodesicLineExact.ArcPosition}.

1277 @kwarg name: Optional C{B{name}=NN} (C{str}).

1278

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

1280 '''

1281 _xinstanceof(GeodesicExact, geodesic=geodesic)

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

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

1284# _update_all(geodesic)

1285 _GeodesicLineExact.__init__(self, geodesic, lat1, lon1, azi1, caps, 0, **name)

1286

1287

1288 def _Astroid(x, y):

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

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

1291 '''

1292 p = x**2

1293 q = y**2

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

1295 if r > 0 or q:

1296 # avoid possible division by zero when r = 0

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

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

1299 if r:

1300 r = r / _6_0 # /= chokes PyChecker

1301 r3 = r**3

1302 T3 = r3 + S

1303 # discriminant of the quadratic equation for T3 is

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

1305 d = (r3 + T3) * S

1306 if d < 0:

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

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

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

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

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

1312 else:

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

1314 # minimize loss of precision due to cancellation.

1315 if d:

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

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

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

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

1320 u += r**2 / u

1321 u += r

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

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

1324 else:

1325 u = _0_0

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

1327 # avoid loss of accuracy when u < 0

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

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

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

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

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

1333

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

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

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

1337 k = _0_0

1338

1339 return k

1340

1341

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

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

1344 '''

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

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

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

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

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

1350 n = _xnC4(nC4=nC4)

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

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

1353 return _coeffs

1354

1355

1356__all__ += _ALL_DOCS(GeodesicExact, GeodesicLineExact)

1357

1358# **) MIT License

1359#

1360# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.

1361#

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

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

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

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

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

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

1368#

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

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

1371#

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

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

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

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

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

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

1378# OTHER DEALINGS IN THE SOFTWARE.