1

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

3

4 u'''Wrapper around several C{geomath.Math} functions from I{Karney}'s Python package U{geographiclib

5<https://PyPI.org/project/geographiclib>}, provided that package is installed.

6

7 The I{wrapped} class methods return a L{GDict} instance offering access to the C{dict} items

8 either by C{key} or by C{attribute} name.

9 All methods of the I{wrapped} L{Geodesic<geodesicw.Geodesic>} and L{GeodesicLine<geodesicw.GeodesicLine>}

10 classes return a L{GDict} instance offering access to the C{dict} items either by C{key} or by

11 C{attribute} name.

12

13 With env variable C{PYGEODESY_GEOGRAPHICLIB} left undefined or set to C{"2"}, modules L{geodesicx},

14 L{geodesicw} and this module will use U{GeographicLib 2.0<https://GeographicLib.SourceForge.io/C++/doc/>}

15 and newer transcoding, otherwise C{1.52} or older.

16

17 Karney-based functionality

18==========================

19

20 1. The following classes and functions in C{pygeodesy}

21

22 - L{AlbersEqualArea}, L{AlbersEqualArea2}, L{AlbersEqualArea4},

23 L{AlbersEqualAreaCylindrical}, L{AlbersEqualAreaNorth}, L{AlbersEqualAreaSouth} --

24 U{AlbersEqualArea<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1AlbersEqualArea.html>}

25

26 - L{AuxAngle}, L{AuxDST}, L{AuxDLat}, L{AuxLat} -- U{AuxAngle

27 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1AuxAngle.html>},

28 U{DST<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1DST.html>},

29 U{DAuxLatitude<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1DAuxLatitude.html>},

30 U{AuxLatitude<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1AuxLatitude.html>} in I{GeographicLib 2.2+}

31

32 - L{CassiniSoldner} -- U{CassiniSoldner<https://GeographicLib.SourceForge.io/C++/doc/

33 classGeographicLib_1_1CassiniSoldner.html>}

34

35 - L{EcefKarney} -- U{Geocentric<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Geocentric.html>}

36

37 - L{Elliptic} -- U{EllipticFunction<https://GeographicLib.SourceForge.io/C++/doc/

38 classGeographicLib_1_1EllipticFunction.html>}

39

40 - L{EquidistantExact}, L{EquidistantGeodSolve}, L{EquidistantKarney} -- U{AzimuthalEquidistant

41 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1AzimuthalEquidistant.html>}

42

43 - L{Etm}, L{ExactTransverseMercator} -- U{TransverseMercatorExact

44 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1TransverseMercatorExact.html>}

45

46 - L{Geodesic}, L{GeodesicLine} -- I{wrapped} U{geodesic.Geodesic<https://PyPI.org/project/geographiclib>},

47 I{wrapped} U{geodesicline.GeodesicLine<https://PyPI.org/project/geographiclib>}

48

49 - L{GeodesicAreaExact}, L{PolygonArea} -- U{PolygonArea<https://GeographicLib.SourceForge.io/C++/doc/

50 classGeographicLib_1_1PolygonAreaT.html>}

51

52 - L{GeodesicExact}, L{GeodesicLineExact} -- U{GeodesicExact<https://GeographicLib.SourceForge.io/C++/doc/

53 classGeographicLib_1_1GeodesicExact.html>}, U{GeodesicLineExact<https://GeographicLib.SourceForge.io/C++/doc/

54 classGeographicLib_1_1GeodesicLineExact.html>}

55

56 - L{GeoidKarney} -- U{Geoid<https://GeographicLib.SourceForge.io/C++/doc/geoid.html>}

57

58 - L{Georef} -- U{Georef<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Georef.html>}

59

60 - L{GnomonicExact}, L{GnomonicGeodSolve}, L{GnomonicKarney} -- U{Gnomonic

61 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Gnomonic.html>}

62

63 - L{JacobiConformal} -- U{JacobiConformal

64 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1JacobiConformal.html#details>}

65

66 - L{KTransverseMercator} - U{TransverseMercator

67 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1TransverseMercator.html>}

68

69 - L{LocalCartesian}, L{Ltp} -- U{LocalCartesian<https://GeographicLib.SourceForge.io/C++/doc/

70 classGeographicLib_1_1LocalCartesian.html>}

71

72 - L{Osgr} -- U{OSGB<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1OSGB.html>}

73

74 - L{rhumb.aux_}, L{RhumbAux}, L{RhumbLineAux} -- U{Rhumb

75 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Rhumb.html>} and U{RhumbLine

76 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1RhumbLine.html>} from I{GeographicLib 2.2+}

77

78 - L{rhumb.ekx}, L{Rhumb}, L{RhumbLine} -- U{Rhumb

79 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Rhumb.html>},

80 U{RhumbLine<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1RhumbLine.html>},

81 U{TransverseMercator<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1TransverseMercator.html>}

82 from I{GeographicLib 2.0}

83

84 - L{Ups} -- U{PolarStereographic<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1PolarStereographic.html>}

85

86 - L{Utm} -- U{TransverseMercator<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1TransverseMercator.html>}

87

88 - L{UtmUps}, L{Epsg} -- U{UTMUPS<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1UTMUPS.html>}

89

90 - L{atan1d}, L{atan2d}, L{sincos2}, L{sincos2d}, L{tand} -- U{geomath.Math

91 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Math.html>}

92

93 are I{transcoded} from C++ classes in I{Karney}'s U{GeographicLib<https://GeographicLib.SourceForge.io/C++/doc/annotated.html>}.

94

95 2. These C{pygeodesy} modules and classes

96

97 - L{ellipsoidalGeodSolve}, L{ellipsoidalKarney}, L{geodsolve}, L{karney}, L{rhumb.solve}

98 - L{EquidistantKarney}, L{FrechetKarney}, L{GeodesicSolve}, L{GeodesicLineSolve}, L{GnomonicGeodSolve},

99 L{GnomonicKarney}, L{HeightIDWkarney}

100

101 are or use I{wrappers} around I{Karney}'s Python U{geographiclib<https://PyPI.org/project/geographiclib>}

102 C{geodesic}, C++ utility U{GeodSolve<https://GeographicLib.SourceForge.io/C++/doc/GeodSolve.1.html>} or

103 C++ utility U{RhumbSolve<https://GeographicLib.SourceForge.io/C++/doc/RhumbSolve.1.html>}.

104

105 3. All C{pygeodesy} functions and methods to compute I{ellipsoidal} intersections, nearest points and trilaterations

106

107 - L{ellipsoidalExact.intersection3}, L{ellipsoidalExact.intersections2}, L{ellipsoidalExact.nearestOn},

108 L{ellipsoidalExact.LatLon.intersection3}, L{ellipsoidalExact.LatLon.intersections2},

109 L{ellipsoidalExact.LatLon.nearestOn}, L{ellipsoidalExact.LatLon.trilaterate5}

110

111 - L{ellipsoidalKarney.intersection3}, L{ellipsoidalKarney.intersections2}, L{ellipsoidalKarney.nearestOn},

112 L{ellipsoidalKarney.LatLon.intersection3}, L{ellipsoidalKarney.LatLon.intersections2},

113 L{ellipsoidalKarney.LatLon.nearestOn}, L{ellipsoidalKarney.LatLon.trilaterate5}

114

115 - L{ellipsoidalVincenty.intersection3}, L{ellipsoidalVincenty.intersections2}, L{ellipsoidalVincenty.nearestOn},

116 L{ellipsoidalVincenty.LatLon.intersection3}, L{ellipsoidalVincenty.LatLon.intersections2},

117 L{ellipsoidalVincenty.LatLon.nearestOn}, L{ellipsoidalVincenty.LatLon.trilaterate5}

118

119 - L{RhumbLineAux.Intersection} and L{RhumbLine.Intersection}

120

121 are implementations of I{Karney}'s iterative solution posted under U{The B{ellipsoidal} case

122<https://GIS.StackExchange.com/questions/48937/calculating-intersection-of-two-circles>} and in paper U{Geodesics

123 on an ellipsoid of revolution<https://ArXiv.org/pdf/1102.1215.pdf>} (pp 20-21, section B{14. MARITIME BOUNDARIES}).

124

125 4. The C{pygeodesy} methods to compute I{ellipsoidal} intersections and nearest points

126

127 - L{RhumbLineAux.Intersecant2}, L{RhumbLineAux.PlumbTo}, L{RhumbLine.Intersecant2} and L{RhumbLine.PlumbTo}

128

129 are I{transcoded} of I{Karney}'s iterative C++ function U{rhumb-intercept

130<https://SourceForge.net/p/geographiclib/discussion/1026620/thread/2ddc295e/>}.

131

132 5. Spherical functions

133

134 - L{pygeodesy.excessKarney_}, L{sphericalTrigonometry.areaOf}

135

136 in C{pygeodesy} are based on I{Karney}'s post U{Area of a spherical polygon

137<https://MathOverflow.net/questions/97711/the-area-of-spherical-polygons>}, 3rd Answer.

138'''

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

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

141

142 from pygeodesy.basics import _copysign, int1s, isint, neg, unsigned0, \

143 _xgeographiclib, _xImportError, _xversion_info, \

144 _xinstanceof, _zip, isodd # PYCHOK shared

145 from pygeodesy.constants import NAN, _isfinite as _math_isfinite, _0_0, \

146 _1_16th, _1_0, _2_0, _180_0, _N_180_0, _360_0

147 from pygeodesy.errors import GeodesicError, itemsorted, _ValueError, _xkwds, \

148 _xkwds_get

149 from pygeodesy.fmath import cbrt, fremainder, hypot as _hypot, norm2, \

150 euclid, Fsum, unstr # PYCHOK shared

151# from pygeodesy.fsums import Fsum # from .fmath

152 from pygeodesy.interns import NN, _2_, _a12_, _area_, _azi2_, _azi12_, \

153 _composite_, _lat1_, _lat2_, _lon1_, _lon2_, \

154 _m12_, _M12_, _M21_, _number_, _s12_, _S12_, \

155 _UNDER_, _BAR_ # PYCHOK used!

156 from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS, _getenv

157 from pygeodesy.named import ADict, _NamedBase, _NamedTuple, notImplemented, _Pass

158 from pygeodesy.props import deprecated_method, Property_RO, property_RO # PYCHOK shared

159# from pygeodesy.streps import unstr # from .fmath

160 from pygeodesy.units import Bearing as _Azi, Degrees as _Deg, Lat, Lon, \

161 Meter as _M, Meter2 as _M2, Number_, \

162 Precision_, _1mm as _TOL_M # PYCHOK shared

163 from pygeodesy.utily import atan2d, sincos2d, tand, _unrollon, fabs

164

165# from math import fabs # from .utily

166

167__all__ = _ALL_LAZY.karney

168__version__ = '24.02.02'

169

170_K_2_0 = _getenv('PYGEODESY_GEOGRAPHICLIB', _2_) == _2_

171_perimeter_ = 'perimeter'

172

173

174 class _GTuple(_NamedTuple): # in .testNamedTuples

175 '''(INTERNAL) Helper.

176 '''

177 def toGDict(self, **updates):

178 '''Convert this C{*Tuple} to a L{GDict}.

179

180 @kwarg updates: Optional items to apply (C{nam=value} pairs)

181 '''

182 r = GDict(_zip(self._Names_, self)) # strict=True

183 if updates:

184 r.update(updates)

185 if self._iteration is not None:

186 r._iteration = self._iteration

187 return r

188

189

190 class _Lat(Lat):

191 '''(INTERNAL) Latitude B{C{lat}}.

192 '''

193 def __init__(self, *lat, **Error_name):

194 kwds = _xkwds(Error_name, clip=0, Error=GeodesicError)

195 Lat.__new__(_Lat, *lat, **kwds)

196

197

198 class _Lon(Lon):

199 '''(INTERNAL) Longitude B{C{lon}}.

200 '''

201 def __init__(self, *lon, **Error_name):

202 kwds = _xkwds(Error_name, clip=0, Error=GeodesicError)

203 Lon.__new__(_Lon, *lon, **kwds)

204

205

206 class Area3Tuple(_NamedTuple): # in .geodesicx.gxarea

207 '''3-Tuple C{(number, perimeter, area)} with the C{number}

208 of points of the polygon or polyline, the C{perimeter} in

209 C{meter} and the C{area} in C{meter} I{squared}.

210 '''

211 _Names_ = (_number_, _perimeter_, _area_)

212 _Units_ = ( Number_, _M, _M2)

213

214

215 class Caps(object): # PYCHOK

216 '''(INTERNAL) Overriden by C{Caps} below.

217 '''

218 EMPTY = 0 # formerly aka NONE

219 _CAP_1 = 1 << 0 # for goedesicw only

220 _CAP_1p = 1 << 1 # for goedesicw only

221# _CAP_2 = 1 << 2

222 _CAP_3 = 1 << 3 # for goedesicw only

223# _CAP_4 = 1 << 4

224# _CAP_ALL = 0x1F

225# _CAP_MASK = _CAP_ALL

226 LATITUDE = 1 << 7 # compute latitude C{lat2}

227 LONGITUDE = 1 << 8 # compute longitude C{lon2} _CAP_3

228 AZIMUTH = 1 << 9 # azimuths C{azi1} and C{azi2}

229 DISTANCE = 1 << 10 # compute distance C{s12} _CAP_1

230 DISTANCE_IN = 1 << 11 # allow distance C{s12} in Direct _CAP_1 | _CAP_1p

231 REDUCEDLENGTH = 1 << 12 # compute reduced length C{m12} _CAP_1 | _CAP_2

232 GEODESICSCALE = 1 << 13 # compute geodesic scales C{M12} and C{M21} _CAP_1 | _CAP_2

233 AREA = 1 << 14 # compute area C{S12} _CAP_4

234

235 STANDARD = AZIMUTH | DISTANCE | DISTANCE_IN | LATITUDE | LONGITUDE

236 ALL = 0x7F80 # without LONG_UNROLL, LINE_OFF, REVERSE2 and _DEBUG_*

237

238 _DIRECT3 = AZIMUTH | LATITUDE | LONGITUDE | _CAP_3 # for goedesicw only

239 _INVERSE3 = AZIMUTH | DISTANCE | _CAP_1 # for goedesicw only

240 _STD = STANDARD | _CAP_3 | _CAP_1 # for goedesicw only

241 _STD_LINE = _STD | _CAP_1p # for goedesicw only

242

243 LINE_OFF = 1 << 15 # Line without updates from parent geodesic or rhumb

244 LONG_UNROLL = 1 << 16 # unroll C{lon2} in .Direct and .Position

245 REVERSE2 = 1 << 17 # reverse C{azi2}

246

247 LATITUDE_LONGITUDE = LATITUDE | LONGITUDE

248 LATITUDE_LONGITUDE_AREA = LATITUDE | LONGITUDE | AREA

249

250 AZIMUTH_DISTANCE = AZIMUTH | DISTANCE

251 AZIMUTH_DISTANCE_AREA = AZIMUTH | DISTANCE | AREA

252

253 _ANGLE_ONLY = 1 << 18 # angular distance C{a12} only

254 _SALPs_CALPs = 1 << 19 # (INTERNAL) GeodesicExact._GenInverse

255

256 _DEBUG_AREA = 1 << 20 # (INTERNAL) include Line details

257 _DEBUG_DIRECT = 1 << 21 # (INTERNAL) include Direct details

258 _DEBUG_INVERSE = 1 << 22 # (INTERNAL) include Inverse details

259 _DEBUG_LINE = 1 << 23 # (INTERNAL) include Line details

260 _DEBUG_ALL = _DEBUG_AREA | _DEBUG_DIRECT | _DEBUG_INVERSE | \

261 _DEBUG_LINE | _ANGLE_ONLY | _SALPs_CALPs

262

263 _OUT_ALL = ALL

264 _OUT_MASK = ALL | LONG_UNROLL | REVERSE2 | _DEBUG_ALL

265

266 _AZIMUTH_LATITUDE_LONGITUDE = AZIMUTH | LATITUDE | LONGITUDE

267 _DEBUG_DIRECT_LINE = _DEBUG_DIRECT | _DEBUG_LINE

268# _DISTANCE_IN_OUT = DISTANCE_IN & _OUT_MASK # == DISTANCE_IN in .gx, .gxline

269 _LINE = AZIMUTH | LATITUDE | LONG_UNROLL

270 _REDUCEDLENGTH_GEODESICSCALE = REDUCEDLENGTH | GEODESICSCALE

271# _REDUCEDLENGTH_GEODESICSCALE_DISTANCE = REDUCEDLENGTH | GEODESICSCALE | DISTANCE

272

273 def toStr(self, Csk, sep=_BAR_):

274 '''Return a C{Caps} or C{outmask} as C{str} or tuple of C{str}s.

275 '''

276 s = []

277 for c, C in itemsorted(self.__class__.__dict__):

278 if isint(C) and (Csk & C) and int1s(C) == 1 \

279 and (C in (Caps.REVERSE2, Caps._SALPs_CALPs)

280 or c.replace(_UNDER_, NN).isupper()):

281 s.append(c)

282 return sep.join(s) if sep else tuple(s)

283

284 Caps = Caps() # PYCHOK singleton

285'''I{Enum}-style masks to be bit-C{or}'ed to specify geodesic or

286 rhumb capabilities (C{caps}) and expected results (C{outmask}).

287

288 C{AREA} - compute area C{S12},

289

290 C{AZIMUTH} - include azimuths C{azi1} and C{azi2},

291

292 C{DISTANCE} - compute distance C{s12},

293

294 C{DISTANCE_IN} - allow distance C{s12} in C{.Direct},

295

296 C{EMPTY} - nothing, formerly aka C{NONE},

297

298 C{GEODESICSCALE} - compute geodesic scales C{M12} and C{M21},

299

300 C{LATITUDE} - compute latitude C{lat2},

301

302 C{LINE_OFF} - Line without updates from parent geodesic or rhumb.

303

304 C{LONGITUDE} - compute longitude C{lon2},

305

306 C{LONG_UNROLL} - unroll C{lon2} in C{.Direct},

307

308 C{REDUCEDLENGTH} - compute reduced length C{m12},

309

310 C{REVERSE2} - reverse C{azi2},

311

312 and C{ALL} - all of the above.

313

314 C{STANDARD} = C{AZIMUTH | DISTANCE | DISTANCE_IN | LATITUDE | LONGITUDE}'''

315

316

317 class _CapsBase(_NamedBase): # in .auxilats, .geodesicx.gxbases

318 '''(INTERNAL) Base class for C{[_]Geodesic*Exact}.

319 '''

320 ALL = Caps.ALL

321 AREA = Caps.AREA

322 AZIMUTH = Caps.AZIMUTH

323 DISTANCE = Caps.DISTANCE

324 DISTANCE_IN = Caps.DISTANCE_IN

325 EMPTY = Caps.EMPTY # aka NONE

326 GEODESICSCALE = Caps.GEODESICSCALE

327 LATITUDE = Caps.LATITUDE

328 LINE_OFF = Caps.LINE_OFF

329 LONGITUDE = Caps.LONGITUDE

330 LONG_UNROLL = Caps.LONG_UNROLL

331 REDUCEDLENGTH = Caps.REDUCEDLENGTH

332 STANDARD = Caps.STANDARD

333

334 _caps = 0 # None

335 _debug = 0 # or Caps._DEBUG_...

336

337 @Property_RO

338 def caps(self):

339 '''Get the capabilities (bit-or'ed C{Caps}).

340 '''

341 return self._caps

342

343 def caps_(self, caps):

344 '''Check the available capabilities.

345

346 @arg caps: Bit-or'ed combination of L{Caps} values

347 for all capabilities to be checked.

348

349 @return: C{True} if I{all} B{C{caps}} are available,

350 C{False} otherwise (C{bool}).

351 '''

352 caps &= Caps._OUT_ALL

353 return (self.caps & caps) == caps

354

355 @property

356 def debug(self):

357 '''Get the C{debug} option (C{bool}).

358 '''

359 return bool(self._debug)

360

361 @debug.setter # PYCHOK setter!

362 def debug(self, debug):

363 '''Set the C{debug} option (C{bool}) to include

364 more details in L{GDict} results.

365 '''

366 self._debug = Caps._DEBUG_ALL if debug else 0

367

368 def _iter2tion(self, r, s):

369 '''(INTERNAL) Copy C{C{s}.iter} into C{B{r}._iteration}.

370 '''

371 i = _xkwds_get(s, iter=None)

372 if i is not None:

373 self._iteration = r._iteration = i

374 return r

375

376

377 class Direct9Tuple(_GTuple):

378 '''9-Tuple C{(a12, lat2, lon2, azi2, s12, m12, M12, M21, S12)} with arc

379 length C{a12}, angles C{lat2}, C{lon2} and azimuth C{azi2} in C{degrees},

380 distance C{s12} and reduced length C{m12} in C{meter} and area C{S12} in

381 C{meter} I{squared}.

382 '''

383 _Names_ = (_a12_, _lat2_, _lon2_, _azi2_, _s12_, _m12_, _M12_, _M21_, _S12_)

384 _Units_ = (_Azi, _Lat, _Lon, _Azi, _M, _Pass, _Pass, _Pass, _M2)

385

386

387 class GDict(ADict): # XXX _NamedDict

388 '''A C{dict} with both C{key} I{and} C{attribute} access to the C{dict} items.

389

390 Results of all C{geodesic} and C{rhumb} methods (with capitalized named) are

391 returned as L{GDict} instances, see for example L{GeodesicExact} and L{RhumbAux}.

392 '''

393 def toDirect9Tuple(self, dflt=NAN):

394 '''Convert this L{GDict} result to a 9-tuple, like I{Karney}'s method

395 C{geographiclib.geodesic.Geodesic._GenDirect}.

396

397 @kwarg dflt: Default value for missing items (C{any}).

398

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

400 s12, m12, M12, M21, S12)}

401 '''

402 return self._toTuple(Direct9Tuple, dflt)

403

404 def toGeodSolve12Tuple(self, dflt=NAN): # PYCHOK 12 args

405 '''Convert this L{GDict} result to a 12-Tuple, compatible with I{Karney}'s

406 U{GeodSolve<https://GeographicLib.SourceForge.io/C++/doc/GeodSolve.1.html>}

407 result.

408

409 @kwarg dflt: Default value for missing items (C{any}).

410

411 @return: L{GeodSolve12Tuple}C{(lat1, lon1, azi1, lat2, lon2, azi2,

412 s12, a12, m12, M12, M21, S12)}.

413 '''

414 return self._toTuple(_MODS.geodsolve.GeodSolve12Tuple, dflt)

415

416 def toInverse10Tuple(self, dflt=NAN):

417 '''Convert this L{GDict} result to a 10-tuple, like I{Karney}'s

418 method C{geographiclib.geodesic.Geodesic._GenInverse}.

419

420 @kwarg dflt: Default value for missing items (C{any}).

421

422 @return: L{Inverse10Tuple}C{(a12, s12, salp1, calp1,

423 salp2, calp2, m12, M12, M21, S12)}.

424 '''

425 return self._toTuple(Inverse10Tuple, dflt)

426

427 @deprecated_method

428 def toRhumb7Tuple(self, dflt=NAN): # PYCHOK no cover

429 '''DEPRECATED, used method C{toRhumb8Tuple}.

430

431 @return: A I{DEPRECATED} L{Rhumb7Tuple}.

432 '''

433 return self._toTuple(_MODS.deprecated.classes.Rhumb7Tuple, dflt)

434

435 def toRhumb8Tuple(self, dflt=NAN):

436 '''Convert this L{GDict} result to a 8-tuple.

437

438 @kwarg dflt: Default value for missing items (C{any}).

439

440 @return: L{Rhumb8Tuple}C{(lat1, lon1, lat2, lon2,

441 azi12, s12, S12, a12)}.

442 '''

443 return self._toTuple(Rhumb8Tuple, dflt)

444

445 def toRhumbSolve7Tuple(self, dflt=NAN):

446 '''Convert this L{GDict} result to a 8-tuple.

447

448 @kwarg dflt: Default value for missing items (C{any}).

449

450 @return: L{RhumbSolve7Tuple}C{(lat1, lon1, lat2, lon2,

451 azi12, s12, S12)}.

452 '''

453 return self._toTuple(_MODS.rhumb.solve.RhumbSolve7Tuple, dflt)

454

455 def _toTuple(self, nTuple, dflt):

456 '''(INTERNAL) Convert this C{GDict} to an B{C{nTuple}}.

457 '''

458 _g = getattr

459 t = tuple(_g(self, n, dflt) for n in nTuple._Names_)

460 return nTuple(t, iteration=self._iteration)

461

462

463 class Inverse10Tuple(_GTuple):

464 '''10-Tuple C{(a12, s12, salp1, calp1, salp2, calp2, m12, M12, M21, S12)} with arc length

465 C{a12} in C{degrees}, distance C{s12} and reduced length C{m12} in C{meter}, area

466 C{S12} in C{meter} I{squared} and the sines C{salp1}, C{salp2} and cosines C{calp1},

467 C{calp2} of the initial C{1} and final C{2} (forward) azimuths.

468 '''

469 _Names_ = (_a12_, _s12_, 'salp1', 'calp1', 'salp2', 'calp2', _m12_, _M12_, _M21_, _S12_)

470 _Units_ = (_Azi, _M, _Pass, _Pass, _Pass, _Pass, _Pass, _Pass, _Pass, _M2)

471

472 def toGDict(self, **updates):

473 '''Convert this C{Inverse10Tuple} to a L{GDict}.

474

475 @kwarg updates: Optional items to apply (C{nam=value} pairs)

476 '''

477 return _GTuple.toGDict(self, azi1=atan2d(self.salp1, self.calp1), # PYCHOK indent, namedTuple

478 azi2=atan2d(self.salp2, self.calp2), # PYCHOK namedTuple

479 **updates) # PYCHOK indent

480

481

482 class _kWrapped(object): # in .geodesicw

483 ''''(INTERNAL) Wrapper around I{Karney}'s U{geographiclib

484 <https://PyPI.org/project/geographiclib>}.

485 '''

486

487 @Property_RO

488 def geographiclib(self):

489 '''Lazily import C{geographiclib}, provided the U{geographiclib

490 <https://PyPI.org/project/geographiclib>} package is installed,

491 otherwise a C{LazyImportError}.

492 '''

493 g = _xgeographiclib(self.__class__, 1, 49)

494 from geographiclib.geodesic import Geodesic

495 g.Geodesic = Geodesic

496 from geographiclib.geodesicline import GeodesicLine

497 g.GeodesicLine = GeodesicLine

498 from geographiclib.geomath import Math

499 g.Math = Math

500 return g

501

502 @Property_RO

503 def Math(self):

504 '''Wrap the C{geomath.Math} class, provided the U{geographiclib

505 <https://PyPI.org/project/geographiclib>} package is installed,

506 otherwise C{None}.

507 '''

508 try:

509 g = self.geographiclib

510 M = g.Math

511 if _xversion_info(g) < (2,):

512 if _K_2_0:

513 M = None

514# elif not _K_2_0: # XXX set 2.0?

515# _K_2_0 = True

516 except (AttributeError, ImportError):

517 M = None

518 return M

519

520_wrapped = _kWrapped() # PYCHOK singleton, .datum, .test/base.py

521

522

523 class Rhumb8Tuple(_GTuple):

524 '''8-Tuple C{(lat1, lon1, lat2, lon2, azi12, s12, S12, a12)} with lat- C{lat1},

525 C{lat2} and longitudes C{lon1}, C{lon2} of both points, the azimuth of the

526 rhumb line C{azi12}, the distance C{s12}, the area C{S12} under the rhumb

527 line and the angular distance C{a12} between both points.

528 '''

529 _Names_ = (_lat1_, _lon1_, _lat2_, _lon2_, _azi12_, _s12_, _S12_, _a12_)

530 _Units_ = ( Lat, Lon, Lat, Lon, _Azi, _M, _M2, _Deg)

531

532 def toDirect9Tuple(self, dflt=NAN, **a12_azi1_azi2_m12_M12_M21):

533 '''Convert this L{Rhumb8Tuple} result to a 9-tuple, like I{Karney}'s

534 method C{geographiclib.geodesic.Geodesic._GenDirect}.

535

536 @kwarg dflt: Default value for missing items (C{any}).

537 @kwarg a12_azi1_azi2_m12_M12_M21: Optional keyword arguments

538 to specify or override L{Inverse10Tuple} items.

539

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

541 m12, M12, M21, S12)}

542 '''

543 d = dict(azi1=self.azi12, M12=_1_0, m12=self.s12, # PYCHOK attr

544 azi2=self.azi12, M21=_1_0) # PYCHOK attr

545 if a12_azi1_azi2_m12_M12_M21:

546 d.update(a12_azi1_azi2_m12_M12_M21)

547 return self._toTuple(Direct9Tuple, dflt, d)

548

549 def toInverse10Tuple(self, dflt=NAN, **a12_m12_M12_M21_salp1_calp1_salp2_calp2):

550 '''Convert this L{Rhumb8Tuple} to a 10-tuple, like I{Karney}'s

551 method C{geographiclib.geodesic.Geodesic._GenInverse}.

552

553 @kwarg dflt: Default value for missing items (C{any}).

554 @kwarg a12_m12_M12_M21_salp1_calp1_salp2_calp2: Optional keyword

555 arguments to specify or override L{Inverse10Tuple} items.

556

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

558 m12, M12, M21, S12)}.

559 '''

560 s, c = sincos2d(self.azi12) # PYCHOK attr

561 d = dict(salp1=s, calp1=c, M12=_1_0, m12=self.s12, # PYCHOK attr

562 salp2=s, calp2=c, M21=_1_0)

563 if a12_m12_M12_M21_salp1_calp1_salp2_calp2:

564 d.update(a12_m12_M12_M21_salp1_calp1_salp2_calp2)

565 return self._toTuple(Inverse10Tuple, dflt, d)

566

567 def _toTuple(self, nTuple, dflt, updates={}):

568 '''(INTERNAL) Convert this C{Rhumb8Tuple} to an B{C{nTuple}}.

569 '''

570 _g = self.toGDict(**updates).get

571 t = tuple(_g(n, dflt) for n in nTuple._Names_)

572 return nTuple(t, name=self.name)

573

574 @deprecated_method

575 def _to7Tuple(self):

576 '''DEPRECATED, do not use!'''

577 return _MODS.deprecated.classes.Rhumb7Tuple(self[:-1])

578

579

580 def _around(x): # in .utily.sincos2d

581 '''I{Coarsen} a scalar by rounding small values to underflow to C{0.0}.

582

583 @return: Coarsened value (C{float}).

584

585 @see: I{Karney}'s U{geomath.Math.AngRound<https://SourceForge.net/p/

586 geographiclib/code/ci/release/tree/python/geographiclib/geomath.py>}

587 '''

588 try:

589 return _wrapped.Math.AngRound(x)

590 except AttributeError:

591 if x:

592 y = _1_16th - fabs(x)

593 if y > 0: # fabs(x) < _1_16th

594 x = _copysign(_1_16th - y, x)

595 else:

596 x = _0_0 # -0 to 0

597 return x

598

599

600 def _atan2d(y, x):

601 '''Return C{atan2(B{y}, B{x})} in C{degrees}.

602 '''

603 try:

604 return _wrapped.Math.atan2d(y, x)

605 except AttributeError:

606 return atan2d(y, x)

607

608

609 def _cbrt(x):

610 '''Return C{cubic root(B{x})}.

611 '''

612 try:

613 return _wrapped.Math.cbrt(x)

614 except AttributeError:

615 return cbrt(x)

616

617

618 def _copyBit(x, y):

619 '''Like C{copysign0(B{x}, B{y})}, with C{B{x} > 0}.

620 '''

621 return (-x) if _signBit(y) else x

622

623

624 def _2cos2x(cx, sx): # in .auxDST, .auxLat, .gxbases

625 '''Return M{2 * cos(2 * x)} from cos(x) and sin(x).

626 '''

627 r = cx - sx

628 if r:

629 r *= (cx + sx) * _2_0

630 return r

631

632

633 def _diff182(deg0, deg, K_2_0=False):

634 '''Compute C{deg - deg0}, reduced to C{[-180,180]} accurately.

635

636 @return: 2-Tuple C{(delta_angle, residual)} in C{degrees}.

637 '''

638 try:

639 return _wrapped.Math.AngDiff(deg0, deg)

640 except AttributeError:

641 if K_2_0 or _K_2_0: # geographiclib 2.0

642 _r, _360 = fremainder, _360_0

643 d, t = _sum2(_r(-deg0, _360),

644 _r( deg, _360))

645 d, t = _sum2(_r( d, _360), t)

646 if d in (_0_0, _180_0, _N_180_0):

647 d = _copysign(d, -t if t else (deg - deg0))

648 else:

649 _n = _norm180

650 d, t = _sum2(_n(-deg0), _n(deg))

651 d = _n(d)

652 if t > 0 and d == _180_0:

653 d = _N_180_0

654 d, t = _sum2(d, t)

655 return d, t

656

657

658 def _fix90(deg): # mimick Math.LatFix

659 '''Replace angle in C{degrees} outside [-90,90] by NAN.

660

661 @return: Angle C{degrees} or NAN.

662 '''

663 try:

664 return _wrapped.Math.LatFix(deg)

665 except AttributeError:

666 return NAN if fabs(deg) > 90 else deg

667

668

669 def _isfinite(x): # mimick geomath.Math.isfinite

670 '''Check finiteness of C{x}.

671

672 @return: C{True} if finite.

673 '''

674 try:

675 return _wrapped.Math.isfinite(x)

676 except AttributeError:

677 return _math_isfinite(x) # and fabs(x) <= _MAX

678

679

680 def _norm2(x, y): # mimick geomath.Math.norm

681 '''Normalize C{B{x}} and C{B{y}}.

682

683 @return: 2-Tuple of C{(B{x}, B{y})}, normalized.

684 '''

685 try:

686 return _wrapped.Math.norm(x, y)

687 except AttributeError:

688 return norm2(x, y)

689

690

691 def _norm180(deg): # mimick geomath.Math.AngNormalize

692 '''Reduce angle in C{degrees} to (-180,180].

693

694 @return: Reduced angle C{degrees}.

695 '''

696 try:

697 return _wrapped.Math.AngNormalize(deg)

698 except AttributeError:

699 d = fremainder(deg, _360_0)

700 if d in (_180_0, _N_180_0):

701 d = _copysign(_180_0, deg) if _K_2_0 else _180_0

702 return d

703

704

705 def _polygon(geodesic, points, closed, line, wrap):

706 '''(INTERNAL) Compute the area or perimeter of a polygon,

707 using a L{GeodesicExact}, L{GeodesicSolve} or (if the

708 C{geographiclib} package is installed) a C{Geodesic}

709 or C{geodesicw.Geodesic} instance.

710 '''

711 if not wrap: # capability LONG_UNROLL can't be off

712 notImplemented(None, wrap=wrap, up=3)

713

714 if _MODS.booleans.isBoolean(points):

715 # recursive call for each boolean clip

716

717 def _a_p(clip, *args, **unused):

718 return _polygon(geodesic, clip, *args)

719

720 if not closed: # closed only

721 raise _ValueError(closed=closed, points=_composite_)

722

723 return points._sum1(_a_p, closed, line, wrap)

724

725 gP = geodesic.Polygon(line)

726 _A = gP.AddPoint

727

728 Ps = _MODS.iters.PointsIter(points, loop=1, wrap=wrap) # base=LatLonEllipsoidalBase(0, 0)

729 p1 = p0 = Ps[0]

730

731 # note, lon deltas are unrolled, by default

732 _A(p1.lat, p1.lon)

733 for p2 in Ps.iterate(closed=closed):

734 if wrap and not Ps.looped:

735 p2 = _unrollon(p1, p2)

736 _A(p2.lat, p2.lon)

737 p1 = p2

738 if closed and line and p1 != p0:

739 _A(p0.lat, p0.lon)

740

741 # gP.Compute returns (number_of_points, perimeter, signed area)

742 return gP.Compute(False, True)[1 if line else 2]

743

744

745 def _polynomial(x, cs, i, j): # PYCHOK shared

746 '''(INTERNAL) Like C++ C{GeographicLib.Math.hpp.polyval} but with a

747 different signature and cascaded summation as C{karney._sum2_}.

748

749 @return: M{sum(cs[k] * x**(j - k - 1) for k in range(i, j)}

750 '''

751 # assert 0 <= i <= j <= len(cs)

752# try:

753# return _wrapped.Math.polyval(j - i - 1, cs, i, x)

754# except AttributeError:

755# s, t = cs[i], _0_0

756# for c in cs[i+1:j]:

757# s, t = _sum2_(s * x, t * x, c)

758# return s # + t

759 s, _ = _sum2_(cs[i], _0_0, x=x, *cs[i+1: j])

760 return s # + t

761

762

763 def _remainder(x, y):

764 '''Remainder of C{x / y}.

765

766 @return: Remainder in the range M{[-y / 2, y / 2]}, preserving signed 0.0.

767 '''

768 try:

769 return _wrapped.Math.remainder(x, y)

770 except AttributeError:

771 return fremainder(x, y)

772

773

774 if _K_2_0:

775 from math import cos as _cos, sin as _sin

776

777 def _sincos2(rad):

778 return _sin(rad), _cos(rad)

779

780 _signBit = _MODS.basics.signBit

781 else:

782 _sincos2 = _MODS.utily.sincos2 # PYCHOK shared

783

784 def _signBit(x):

785 '''(INTERNAL) GeographicLib 1.52-.

786 '''

787 return x < 0

788

789

790 def _sincos2d(deg):

791 '''Return sine and cosine of an angle in C{degrees}.

792

793 @return: 2-Tuple C{(sin(B{deg}), cos(B{deg}))}.

794 '''

795 try:

796 return _wrapped.Math.sincosd(deg)

797 except AttributeError:

798 return sincos2d(deg)

799

800

801 def _sincos2de(deg, t):

802 '''Return sine and cosine of a corrected angle in C{degrees}.

803

804 @return: 2-Tuple C{(sin(B{deg}), cos(B{deg}))}.

805 '''

806 try:

807 return _wrapped.Math.sincosde(deg, t)

808 except AttributeError:

809 return sincos2d(deg, adeg=t)

810

811

812 def _sum2(u, v): # mimick geomath.Math.sum, actually sum2

813 '''Error-free summation like C{geomath.Math.sum}.

814

815 @return: 2-Tuple C{(B{u} + B{v}, residual)}.

816

817 @note: The C{residual} can be the same as B{C{u}} or B{C{v}}.

818

819 @see: U{Algorithm 3.1<https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}.

820 '''

821 try:

822 return _wrapped.Math.sum(u, v)

823 except AttributeError:

824 s = u + v

825 r = s - v

826 t = s - r

827 # if Algorithm_3_1:

828 # t = (u - t) + (v + r)

829 # elif C_CPP: # Math::sum C/C++

830 # r -= u

831 # t -= v

832 # t += r

833 # t = -t

834 # else:

835 t = (u - r) + (v - t)

836 return s, t

837

838

839 def _sum2_(s, t, *vs, **x):

840 '''Accumulate any B{C{vs}} into a previous C{_sum2(s, t)}.

841

842 @kwarg x: Optional polynomial C{B{x}=1} (C{scalar}).

843

844 @return: 2-Tuple C{(B{s} + B{t} + sum(B{vs}), residual)}.

845

846 @see: I{Karney's} C++ U{Accumulator<https://GeographicLib.SourceForge.io/

847 html/Accumulator_8hpp_source.html>} comments for more details and

848 function C{_sum2} above.

849

850 @note: NOT "error-free", see C{pygeodesy.test/testKarney.py}.

851 '''

852 x = _xkwds_get(x, x=0)

853

854 _s2, _u0 = _sum2, unsigned0

855 for v in vs:

856 if x:

857 s *= x

858 t *= x

859 if v:

860 t, u = _s2(t, v) # start at the least-

861 if s:

862 s, t = _s2(s, t) # significant end

863 if s:

864 t += u # accumulate u into t

865# elif t: # s == 0 implies t == 0

866# raise _AssertionError(t=t, txt=_not_(_0_))

867 else:

868 s = _u0(u) # result is u, t = 0

869 else:

870 s, t = _u0(t), u

871 return s, t

872

873

874 def _tand(x):

875 '''Return C{tan(B{x})} in C{degrees}.

876 '''

877 try:

878 return _wrapped.Math.tand(x)

879 except AttributeError:

880 return tand(x)

881

882

883 def _unroll2(lon1, lon2, wrap=False): # see .ellipsoidalBaseDI._intersects2

884 '''Unroll B{C{lon2 - lon1}} like C{geodesic.Geodesic.Inverse}.

885

886 @return: 2-Tuple C{(B{lon2} - B{lon1}, B{lon2})} with B{C{lon2}}

887 unrolled if B{C{wrap}} is C{True}, normalized otherwise.

888 '''

889 if wrap:

890 d, t = _diff182(lon1, lon2)

891 lon2, _ = _sum2_(d, t, lon1) # (lon1 + d) + t

892 else:

893 lon2 = _norm180(lon2)

894 return (lon2 - lon1), lon2

895

896

897 def _unsigned2(x):

898 '''(INTERNAL) Unsign B{C{x}}.

899 '''

900 return (neg(x), True) if _signBit(x) else (x, False)

901

902

903__all__ += _ALL_DOCS(_CapsBase)

904

905# **) MIT License

906#

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

908#

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

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

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

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

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

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

915#

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

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

918#

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

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

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

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

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

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

925# OTHER DEALINGS IN THE SOFTWARE.