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, itemsorted, neg, unsigned0, \

143 _xgeographiclib, _zip, _version_info

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

145 _1_16th, _1_0, _2_0, _180_0, _N_180_0, _360_0

146 from pygeodesy.errors import GeodesicError, _ValueError, _xkwds, _xkwds_get1, \

147 _xkwds_kwds, _xkwds_not

148 from pygeodesy.fmath import cbrt, fremainder, norm2

149# from pygeodesy.internals import _version_info # from .basics

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

151 _composite_, _lat1_, _lat2_, _lon1_, _lon2_, \

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

153 _UNDER_, _X_, _BAR_ # PYCHOK used!

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

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

156 from pygeodesy.props import deprecated_method, Property_RO

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

158 Meter as _M, Meter2 as _M2, Number_

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

160

161# from math import fabs # from .utily

162

163__all__ = _ALL_LAZY.karney

164__version__ = '24.07.09'

165

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

167_perimeter_ = 'perimeter'

168

169

170 class _GTuple(_NamedTuple): # in .testNamedTuples

171 '''(INTERNAL) Helper.

172 '''

173 def toGDict(self, **updates): # NO name=NN

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

175

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

177 '''

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

179 if updates:

180 r.update(updates)

181 if self._iteration is not None:

182 r._iteration = self._iteration

183 return r

184

185

186 class _Lat(Lat):

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

188 '''

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

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

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

192

193

194 class _Lon(Lon):

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

196 '''

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

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

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

200

201

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

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

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

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

206 '''

207 _Names_ = (_number_, _perimeter_, _area_)

208 _Units_ = ( Number_, _M, _M2)

209

210

211 class Caps(object): # PYCHOK

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

213 '''

214 EMPTY = 0 # formerly aka NONE

215 _CAP_1 = 1 << 0 # for goedesici/-w

216 _CAP_1p = 1 << 1 # for goedesici/-w

217 _CAP_2 = 1 << 2

218 _CAP_3 = 1 << 3 # for goedesici/-w

219# _CAP_4 = 1 << 4

220# _CAP_ALL = 0x1F

221# _CAP_MASK = _CAP_ALL

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

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

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

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

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

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

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

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

230

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

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

233

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

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

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

237 _STD_LINE = _STD | _CAP_2 | _CAP_1p # for goedesici/-w

238

239 LINE_CAPS = _STD_LINE | REDUCEDLENGTH | GEODESICSCALE # .geodesici only

240

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

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

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

244

245 LATITUDE_LONGITUDE = LATITUDE | LONGITUDE

246 LATITUDE_LONGITUDE_AREA = LATITUDE | LONGITUDE | AREA

247

248 AZIMUTH_DISTANCE = AZIMUTH | DISTANCE

249 AZIMUTH_DISTANCE_AREA = AZIMUTH | DISTANCE | AREA

250

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

252 _S_CALPs_ = 1 << 19 # (INTERNAL) GeodesicExact._GenInverse

253

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

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

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

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

258 _DEBUG_ALL = _DEBUG_AREA | _DEBUG_DIRECT | _DEBUG_INVERSE | \

259 _DEBUG_LINE | _ANGLE_ONLY | _S_CALPs_

260

261 _OUT_ALL = ALL

262 _OUT_MASK = ALL | LONG_UNROLL | REVERSE2 | _DEBUG_ALL

263

264 _AZIMUTH_LATITUDE_LONGITUDE = AZIMUTH | LATITUDE | LONGITUDE

265 _DEBUG_DIRECT_LINE = _DEBUG_DIRECT | _DEBUG_LINE

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

267 _LINE = AZIMUTH | LATITUDE | LONG_UNROLL

268 _REDUCEDLENGTH_GEODESICSCALE = REDUCEDLENGTH | GEODESICSCALE

269# _REDUCEDLENGTH_GEODESICSCALE_DISTANCE = REDUCEDLENGTH | GEODESICSCALE | DISTANCE

270

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

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

273 '''

274 s = []

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

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

277 and (C in (Caps.REVERSE2, Caps._S_CALPs_)

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

279 s.append(c)

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

281

282 Caps = Caps() # PYCHOK singleton

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

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

285

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

287

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

289

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

291

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

293

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

295

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

297

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

299

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

301

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

303

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

305

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

307

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

309

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

311

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

313

314_KEY2Caps = dict(azi2=Caps.AZIMUTH, # see GDict._unCaps

315 lat2=Caps.LATITUDE,

316 lon2=Caps.LONGITUDE,

317 m12 =Caps.REDUCEDLENGTH,

318 M12 =Caps.GEODESICSCALE,

319 M21 =Caps.GEODESICSCALE,

320 s12 =Caps.DISTANCE,

321 S12 =Caps.AREA)

322

323

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

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

326 '''

327 ALL = Caps.ALL

328 AREA = Caps.AREA

329 AZIMUTH = Caps.AZIMUTH

330 DISTANCE = Caps.DISTANCE

331 DISTANCE_IN = Caps.DISTANCE_IN

332 EMPTY = Caps.EMPTY # aka NONE

333 GEODESICSCALE = Caps.GEODESICSCALE

334 LATITUDE = Caps.LATITUDE

335 LINE_CAPS = Caps.LINE_CAPS

336 LINE_OFF = Caps.LINE_OFF

337 LONGITUDE = Caps.LONGITUDE

338 LONG_UNROLL = Caps.LONG_UNROLL

339 REDUCEDLENGTH = Caps.REDUCEDLENGTH

340 STANDARD = Caps.STANDARD

341 _STD_LINE = Caps._STD_LINE # for geodesici

342

343 _caps = 0 # None

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

345

346 @Property_RO

347 def caps(self):

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

349 '''

350 return self._caps

351

352 def caps_(self, caps):

353 '''Check the available capabilities.

354

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

356 for all capabilities to be checked.

357

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

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

360 '''

361 caps &= Caps._OUT_ALL

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

363

364 @property

365 def debug(self):

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

367 '''

368 return bool(self._debug)

369

370 @debug.setter # PYCHOK setter!

371 def debug(self, debug):

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

373 more details in L{GDict} results.

374 '''

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

376

377 def _iter2tion(self, r, iter=None, **unused):

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

379 '''

380 if iter is not None:

381 self._iteration = r._iteration = iter

382 return r

383

384

385 class Direct9Tuple(_GTuple):

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

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

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

389 C{meter} I{squared}.

390 '''

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

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

393

394

395 class GDict(ADict): # XXX _NamedDict

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

397

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

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

400 '''

401 def toDirect9Tuple(self, dflt=NAN):

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

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

404

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

406

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

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

409 '''

410 return self._toTuple(Direct9Tuple, dflt)

411

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

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

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

415 result.

416

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

418

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

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

421 '''

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

423

424 def toInverse10Tuple(self, dflt=NAN):

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

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

427

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

429

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

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

432 '''

433 return self._toTuple(Inverse10Tuple, dflt)

434

435 def _toNAN(self, outmask): # .GeodesicLineExact._GenPosition

436 '''(INTERNAL) Convert this C{GDict} to all C{NAN}s.

437 '''

438 d = dict((n, NAN) for n in GeodSolve12Tuple._Names_)

439 return self.set_(**d)._unCaps(outmask)

440

441 @deprecated_method

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

443 '''DEPRECATED on 23.12.07, use method C{toRhumb8Tuple}.

444

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

446 '''

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

448

449 def toRhumb8Tuple(self, dflt=NAN):

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

451

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

453

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

455 azi12, s12, S12, a12)}.

456 '''

457 return self._toTuple(Rhumb8Tuple, dflt)

458

459 def toRhumbSolve7Tuple(self, dflt=NAN):

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

461

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

463

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

465 azi12, s12, S12)}.

466 '''

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

468

469 def _toTuple(self, nTuple, dflt):

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

471 '''

472 _g = getattr

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

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

475

476 def _2X(self, gl, _2X=_X_): # .Intesectool, .Intersector

477 '''(INTERNAL) Rename attr tail from C{-2} to C{-X} or C{-M}.

478 '''

479 X = GDict(self)

480 for n in (_lat2_, _lon2_, _azi2_, _s12_, _a12_):

481 if n in X: # X._X = X._2

482 X[n[:-1] + _2X] = X.pop(n)

483 v = getattr(gl, n, X)

484 if v is not X: # X._2 = gl._2

485 X[n] = v

486 return X

487

488 def _unCaps(self, outmask): # in .geodsolve

489 '''(INTERNAL) Remove superfluous items.

490 '''

491 for k, m in _KEY2Caps.items():

492 if k in self and not (outmask & m):

493 self.pop(k) # delattr(self, k)

494 return self

495

496

497 class GeodSolve12Tuple(_GTuple):

498 '''12-Tuple C{(lat1, lon1, azi1, lat2, lon2, azi2, s12, a12, m12, M12, M21, S12)} with

499 angles C{lat1}, C{lon1}, C{azi1}, C{lat2}, C{lon2} and C{azi2} and arc C{a12} all in

500 C{degrees}, initial C{azi1} and final C{azi2} forward azimuths, distance C{s12} and

501 reduced length C{m12} in C{meter}, area C{S12} in C{meter} I{squared} and geodesic

502 scale factors C{M12} and C{M21}, both C{scalar}, see U{GeodSolve

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

504 '''

505 # from GeodSolve --help option -f ... lat1 lon1 azi1 lat2 lon2 azi2 s12 a12 m12 M12 M21 S12

506 _Names_ = (_lat1_, _lon1_, _azi1_, _lat2_, _lon2_, _azi2_, _s12_, _a12_, _m12_, _M12_, _M21_, _S12_)

507 _Units_ = (_Lat, _Lon, _Azi, _Lat, _Lon, _Azi, _M, _Deg, _Pass, _Pass, _Pass, _M2)

508

509

510 class Inverse10Tuple(_GTuple):

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

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

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

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

515 '''

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

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

518

519 def toGDict(self, **updates):

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

521

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

523 '''

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

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

526 **updates) # PYCHOK indent

527

528

529 class _kWrapped(object): # in .geodesicw

530 ''''(INTERNAL) Wrapper for some of I{Karney}'s U{geographiclib

531 <https://PyPI.org/project/geographiclib>} classes.

532 '''

533

534 @Property_RO

535 def geographiclib(self):

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

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

538 otherwise raise a C{LazyImportError}.

539 '''

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

541 from geographiclib.geodesic import Geodesic

542 g.Geodesic = Geodesic

543 from geographiclib.geodesicline import GeodesicLine

544 g.GeodesicLine = GeodesicLine

545 from geographiclib.geomath import Math

546 g.Math = Math

547 return g

548

549 @Property_RO

550 def Math(self):

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

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

553 otherwise C{None}.

554 '''

555 try:

556 g = self.geographiclib

557 M = g.Math

558 if _version_info(g) < (2,):

559 if _K_2_0:

560 M = None

561# elif not _K_2_0: # XXX set 2.0?

562# _K_2_0 = True

563 except (AttributeError, ImportError):

564 M = None

565 return M

566

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

568

569

570 class Rhumb8Tuple(_GTuple):

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

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

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

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

575 '''

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

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

578

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

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

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

582

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

584 @kwarg a12_azi1_azi2_m12_M12_M21: Optional keyword arguments

585 to specify or override L{Inverse10Tuple} items.

586

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

588 m12, M12, M21, S12)}

589 '''

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

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

592 if a12_azi1_azi2_m12_M12_M21:

593 d.update(a12_azi1_azi2_m12_M12_M21)

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

595

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

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

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

599

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

601 @kwarg a12_m12_M12_M21_salp1_calp1_salp2_calp2: Optional keyword

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

603

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

605 m12, M12, M21, S12)}.

606 '''

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

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

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

610 if a12_m12_M12_M21_salp1_calp1_salp2_calp2:

611 d.update(a12_m12_M12_M21_salp1_calp1_salp2_calp2)

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

613

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

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

616 '''

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

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

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

620

621 @deprecated_method

622 def _to7Tuple(self):

623 '''DEPRECATED, do not use!'''

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

625

626

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

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

629

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

631

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

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

634 '''

635 try:

636 return _wrapped.Math.AngRound(x)

637 except AttributeError:

638 if x:

639 y = _1_16th - fabs(x)

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

641 x = _copysign(_1_16th - y, x)

642 else:

643 x = _0_0 # -0 to 0

644 return x

645

646

647 def _atan2d(y, x):

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

649 '''

650 try:

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

652 except AttributeError:

653 return atan2d(y, x)

654

655

656 def _cbrt(x):

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

658 '''

659 try:

660 return _wrapped.Math.cbrt(x)

661 except AttributeError:

662 return cbrt(x)

663

664

665 def _copyBit(x, y):

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

667 '''

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

669

670

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

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

673 '''

674 r = cx - sx

675 if r:

676 r *= (cx + sx) * _2_0

677 return r

678

679

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

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

682

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

684 '''

685 try:

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

687 except AttributeError:

688 if K_2_0 or _K_2_0: # geographiclib 2.0

689 _r, _360 = fremainder, _360_0

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

691 _r( deg, _360))

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

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

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

695 else:

696 _n = _norm180

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

698 d = _n(d)

699 if t > 0 and d == _180_0:

700 d = _N_180_0

701 d, t = _sum2(d, t)

702 return d, t

703

704

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

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

707

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

709 '''

710 try:

711 return _wrapped.Math.LatFix(deg)

712 except AttributeError:

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

714

715

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

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

718

719 @return: C{True} if finite.

720 '''

721 try:

722 return _wrapped.Math.isfinite(x)

723 except AttributeError:

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

725

726

727 def _llz2line(line, **llz2):

728 '''(INTERNAL) Set C{line.lat2, .lon2, .azi2} from C{llz2}.

729 '''

730 if llz2:

731 llz2 = _xkwds_not(None, **_xkwds_kwds(llz2, lat2=None, lon2=None, azi2=None))

732 if llz2:

733 line.__dict__.update(llz2)

734 return line

735

736

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

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

739

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

741 '''

742 try:

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

744 except AttributeError:

745 return norm2(x, y)

746

747

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

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

750

751 @return: Reduced angle C{degrees}.

752 '''

753 try:

754 return _wrapped.Math.AngNormalize(deg)

755 except AttributeError:

756 d = fremainder(deg, _360_0)

757 if d in (_180_0, _N_180_0):

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

759 return d

760

761

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

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

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

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

766 or C{geodesicw.Geodesic} instance.

767 '''

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

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

770

771 if _MODS.booleans.isBoolean(points):

772 # recursive call for each boolean clip

773

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

775 return _polygon(geodesic, clip, *args)

776

777 if not closed: # closed only

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

779

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

781

782 gP = geodesic.Polygon(line)

783 _A = gP.AddPoint

784

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

786 p1 = p0 = Ps[0]

787

788 # note, lon deltas are unrolled, by default

789 _A(p1.lat, p1.lon)

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

791 if wrap and not Ps.looped:

792 p2 = _unrollon(p1, p2)

793 _A(p2.lat, p2.lon)

794 p1 = p2

795 if closed and line and p1 != p0:

796 _A(p0.lat, p0.lon)

797

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

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

800

801

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

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

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

805

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

807 '''

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

809# try:

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

811# except AttributeError:

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

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

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

815# return s # + t

816 s = cs[i]

817 i += 1

818 if x and i < j:

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

820 return s # + t

821

822

823 def _remainder(x, y):

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

825

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

827 '''

828 try:

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

830 except AttributeError:

831 return fremainder(x, y)

832

833

834 if _K_2_0:

835 from math import cos as _cos, sin as _sin

836

837 def _sincos2(rad):

838 return _sin(rad), _cos(rad)

839

840 _signBit = _MODS.basics.signBit

841 else:

842 _sincos2 = _MODS.utily.sincos2 # PYCHOK shared

843

844 def _signBit(x):

845 '''(INTERNAL) GeographicLib 1.52-.

846 '''

847 return x < 0

848

849

850 def _sincos2d(deg):

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

852

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

854 '''

855 try:

856 return _wrapped.Math.sincosd(deg)

857 except AttributeError:

858 return sincos2d(deg)

859

860

861 def _sincos2de(deg, t):

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

863

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

865 '''

866 try:

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

868 except AttributeError:

869 return sincos2d(deg, adeg=t)

870

871

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

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

874

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

876

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

878

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

880 '''

881 try:

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

883 except AttributeError:

884 s = u + v

885 r = s - v

886 t = s - r

887 # if Algorithm_3_1:

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

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

890 # r -= u

891 # t -= v

892 # t += r

893 # t = -t

894 # else:

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

896 return s, t

897

898

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

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

901

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

903

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

905

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

907 C++/doc/Accumulator_8hpp_source.html>} comments for more details and

908 function C{_sum2} above.

909

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

911 '''

912 x = _xkwds_get1(x, x=_1_0)

913 p = x != _1_0

914

915 _s2, _u0 = _sum2, unsigned0

916 for v in vs:

917 if p:

918 s *= x

919 t *= x

920 if v:

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

922 if s:

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

924 if s:

925 t += u # accumulate u into t

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

927# raise _AssertionError(t=t, txt_not_=_0_)

928 else:

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

930 else:

931 s, t = _u0(t), u

932 return s, t

933

934

935 def _tand(x):

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

937 '''

938 try:

939 return _wrapped.Math.tand(x)

940 except AttributeError:

941 return tand(x)

942

943

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

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

946

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

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

949 '''

950 if wrap:

951 d, t = _diff182(lon1, lon2)

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

953 else:

954 lon2 = _norm180(lon2)

955 return (lon2 - lon1), lon2

956

957

958 def _unsigned2(x):

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

960 '''

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

962

963

964__all__ += _ALL_DOCS(_CapsBase)

965

966# **) MIT License

967#

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

969#

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

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

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

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

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

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

976#

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

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

979#

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

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

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

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

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

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

986# OTHER DEALINGS IN THE SOFTWARE.