Coverage for pygeodesy/karney.py: 93%

359 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-04-09 11:05 -0400

1 

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

3 

4u'''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 

7Methods of the I{wrapped} L{Geodesic<geodesicw.Geodesic>} and L{GeodesicLine<geodesicw.GeodesicLine>} 

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

9C{attribute} name. 

10 

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

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

13and newer transcoding, otherwise C{1.52} or older. Set C{PYGEODESY_GEOGRAPHICLIB=2.4} to default to the 

14C{Jacobi amplitude} instead of C{Bulirsch}' function in methods L{ExactTransverseMercator.forward 

15<pygeodesy.ExactTransverseMercator.forward>} and L{reverse <pygeodesy.ExactTransverseMercator.reverse>}. 

16 

17Karney-based functionality 

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

19 

201. 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{Intersector} -- U{Intersect 

64 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Intersect.html>} from I{GeographicLib 2.3+} 

65 

66 - L{JacobiConformal} -- U{JacobiConformal 

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

68 

69 - L{KTransverseMercator} - U{TransverseMercator 

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

71 

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

73 classGeographicLib_1_1LocalCartesian.html>} 

74 

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

76 

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

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

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

80 

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

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

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

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

85 from I{GeographicLib 2.0} 

86 

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

88 

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

90 

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

92 

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

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

95 

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

97 

982. These C{pygeodesy} modules and classes 

99 

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

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

102 L{GnomonicKarney}, L{HeightIDWkarney}, L{Intersectool} 

103 

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

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

106U{IntersectTool<https://GeographicLib.SourceForge.io/C++/doc/IntersectTool.1.html>} or 

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

108 

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

110 

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

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

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

114 

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

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

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

118 

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

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

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

122 

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

124 

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

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

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

128 

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

130 

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

132 

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

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

135 

1365. Spherical functions 

137 

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

139 

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

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

142''' 

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

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

145 

146from pygeodesy.basics import _copysign, isint, neg, unsigned0, \ 

147 _xgeographiclib, _zip 

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

149 _1_16th, _1_0, _2_0, _180_0, _N_180_0, _360_0 

150from pygeodesy.errors import GeodesicError, _ValueError, _xkwds 

151from pygeodesy.fmath import cbrt, fremainder, norm2 # Fhorner, Fsum 

152from pygeodesy.internals import _getenv, _popen2, _PYGEODESY, _version_info 

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

154 _composite_, _lat1_, _lat2_, _lon1_, _lon2_, \ 

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

156 _SPACE_, _UNDER_, _X_, _1_, _2_, _BAR_ # PYCHOK used! 

157from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS 

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

159from pygeodesy.props import deprecated_method, Property_RO, property_RO, \ 

160 property_ROnce 

161from pygeodesy.units import Azimuth as _Azi, Degrees as _Deg, Lat, Lon, \ 

162 Meter as _M, Meter2 as _M2, Number_ 

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

164 

165# from math import fabs # from .utily 

166 

167__all__ = _ALL_LAZY.karney 

168__version__ = '25.04.08' 

169 

170_2_4_ = '2.4' 

171_K_2_0 = _getenv(_PYGEODESY(_xgeographiclib, 1), _2_) 

172_K_2_4 = _K_2_0 == _2_4_ 

173_K_2_0 = _K_2_4 or (_K_2_0 == _2_) 

174_perimeter_ = 'perimeter' 

175 

176 

177class _GTuple(_NamedTuple): # in .testNamedTuples 

178 '''(INTERNAL) Helper. 

179 ''' 

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

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

182 

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

184 ''' 

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

186 if updates: 

187 r.update(updates) 

188 if self._iteration is not None: 

189 r._iteration = self._iteration 

190 return r 

191 

192 

193class _Lat(Lat): 

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

195 ''' 

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

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

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

199 

200 

201class _Lon(Lon): 

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

203 ''' 

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

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

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

207 

208 

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

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

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

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

213 ''' 

214 _Names_ = (_number_, _perimeter_, _area_) 

215 _Units_ = ( Number_, _M, _M2) 

216 

217 

218class Caps(object): 

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

220 ''' 

221 EMPTY = 0 # formerly aka NONE 

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

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

224 _CAP_2 = 1 << 2 

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

226 _CAP_4 = 1 << 4 # for goedesicw 

227 _CAP_ALL = 0x1F 

228# _CAP_MASK = _CAP_ALL 

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

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

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

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

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

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

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

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

237 

238 STANDARD = AZIMUTH | DISTANCE | LATITUDE | LONGITUDE 

239 

240 _DIRECT3 = AZIMUTH | LATITUDE | LONGITUDE # for goedesicw only 

241 _INVERSE3 = AZIMUTH | DISTANCE # for goedesicw only 

242 _STD = STANDARD # for goedesicw only 

243 _STD_LINE = _STD | DISTANCE_IN # for goedesici/-w 

244 

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

246 LONG_UNROLL = 1 << 15 # unroll C{lon2} in .Direct and .Position 

247# = 1 << 16 # unused 

248 LINE_OFF = 1 << 17 # Line without updates from parent geodesic or rhumb 

249 REVERSE2 = 1 << 18 # reverse C{azi2} 

250 ALL = 0x7F80 | _CAP_ALL # without LONG_UNROLL, LINE_OFF, REVERSE2 and _DEBUG_* 

251 

252 LATITUDE_LONGITUDE = LATITUDE | LONGITUDE 

253 LATITUDE_LONGITUDE_AREA = LATITUDE | LONGITUDE | AREA 

254 

255 AZIMUTH_DISTANCE = AZIMUTH | DISTANCE 

256 AZIMUTH_DISTANCE_AREA = AZIMUTH | DISTANCE | AREA 

257 

258 _SALP_CALPs_ = 1 << 19 # (INTERNAL) GeodesicExact._GenInverse 

259 

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

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

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

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

264 _DEBUG_ALL = _DEBUG_AREA | _DEBUG_DIRECT | _DEBUG_INVERSE | \ 

265 _DEBUG_LINE | _SALP_CALPs_ 

266 

267 _OUT_ALL = ALL # see geographiclib.geodesiccapabilities.py 

268 _OUT_MASK = ALL | LONG_UNROLL | REVERSE2 | _DEBUG_ALL 

269 

270 _AZIMUTH_LATITUDE_LONGITUDE = AZIMUTH | LATITUDE | LONGITUDE 

271 _AZIMUTH_LATITUDE_LONG_UNROLL = AZIMUTH | LATITUDE | LONG_UNROLL 

272 _DEBUG_DIRECT_LINE = _DEBUG_DIRECT | _DEBUG_LINE 

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

274 _REDUCEDLENGTH_GEODESICSCALE = REDUCEDLENGTH | GEODESICSCALE 

275# _REDUCEDLENGTH_GEODESICSCALE_DISTANCE = REDUCEDLENGTH | GEODESICSCALE | DISTANCE 

276 

277 def items(self): 

278 '''Yield all I{public} C{Caps} as 2-tuple C{(NAME, mask)}. 

279 ''' 

280 for n, C in Caps.__class__.__dict__.items(): 

281 if isint(C) and not n.startswith(_UNDER_) \ 

282 and n.replace(_UNDER_, NN).isupper(): 

283 yield n, C 

284 

285 def toStr(self, Cask, sep=_BAR_): 

286 '''Return C{Caps} or an C{outmask} as C{str} or tuple of C{str}s. 

287 ''' 

288 s = (n for n, C in sorted(Caps.items()) 

289 if C and (Cask & C) == C) # and int1s(C) <= 3 

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

291 

292Caps = Caps() # PYCHOK singleton 

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

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

295 

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

297 

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

299 

300C{DISTANCE} - compute distance C{s12} and angular distance C{a12}, 

301 

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

303 

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

305 

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

307 

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

309 

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

311 

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

313 

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

315 

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

317 

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

319 

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

321 

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

323 

324_key2Caps = dict(a12 =Caps.DISTANCE, # in GDict._unCaps 

325 azi2=Caps.AZIMUTH, 

326 lat2=Caps.LATITUDE, 

327 lon2=Caps.LONGITUDE, 

328 m12 =Caps.REDUCEDLENGTH, 

329 M12 =Caps.GEODESICSCALE, 

330 M21 =Caps.GEODESICSCALE, 

331 s12 =Caps.DISTANCE, 

332 S12 =Caps.AREA) 

333 

334 

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

336 '''(INTERNAL) Base class for C{Geodesic*}, C{Geodesic*Exact}, C{Intersectool} and C{Rhumb*Base}. 

337 ''' 

338 ALL = Caps.ALL 

339 AREA = Caps.AREA 

340 AZIMUTH = Caps.AZIMUTH 

341 DISTANCE = Caps.DISTANCE 

342 DISTANCE_IN = Caps.DISTANCE_IN 

343 EMPTY = Caps.EMPTY # aka NONE 

344 GEODESICSCALE = Caps.GEODESICSCALE 

345 LATITUDE = Caps.LATITUDE 

346 LINE_CAPS = Caps.LINE_CAPS 

347 LINE_OFF = Caps.LINE_OFF 

348 LONGITUDE = Caps.LONGITUDE 

349 LONG_UNROLL = Caps.LONG_UNROLL 

350 REDUCEDLENGTH = Caps.REDUCEDLENGTH 

351 STANDARD = Caps.STANDARD 

352 _STD_LINE = Caps._STD_LINE # for geodesici 

353 

354 _caps = 0 # None 

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

356 

357 @Property_RO 

358 def caps(self): 

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

360 ''' 

361 return self._caps 

362 

363 def caps_(self, caps): 

364 '''Check the available capabilities. 

365 

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

367 for all capabilities to be checked. 

368 

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

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

371 ''' 

372 caps &= Caps._OUT_ALL 

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

374 

375 @property 

376 def debug(self): 

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

378 ''' 

379 return bool(self._debug) 

380 

381 @debug.setter # PYCHOK setter! 

382 def debug(self, debug): 

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

384 more details in L{GDict} results. 

385 ''' 

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

387 

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

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

390 ''' 

391 if iter is not None: 

392 self._iteration = r._iteration = iter 

393 return r 

394 

395 

396class Direct9Tuple(_GTuple): 

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

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

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

400 C{meter} I{squared}. 

401 ''' 

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

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

404 

405 

406class GDict(ADict): # XXX _NamedDict 

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

408 

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

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

411 ''' 

412 def toDirect9Tuple(self, dflt=NAN): 

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

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

415 

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

417 

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

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

420 ''' 

421 return self._toTuple(Direct9Tuple, dflt) 

422 

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

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

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

426 result. 

427 

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

429 

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

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

432 ''' 

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

434 

435 def toInverse10Tuple(self, dflt=NAN): 

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

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

438 

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

440 

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

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

443 ''' 

444 return self._toTuple(Inverse10Tuple, dflt) 

445 

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

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

448 ''' 

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

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

451 

452 @deprecated_method 

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

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

455 

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

457 ''' 

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

459 

460 def toRhumb8Tuple(self, dflt=NAN): 

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

462 

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

464 

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

466 azi12, s12, S12, a12)}. 

467 ''' 

468 return self._toTuple(Rhumb8Tuple, dflt) 

469 

470 def toRhumbSolve7Tuple(self, dflt=NAN): 

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

472 

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

474 

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

476 azi12, s12, S12)}. 

477 ''' 

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

479 

480 def _toTuple(self, nTuple, dflt): 

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

482 ''' 

483 _g = getattr 

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

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

486 

487 def _2X(self, gl, _2X=_X_): # .Intersectool, .Intersector 

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

489 ''' 

490 X = GDict(self) 

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

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

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

494 v = getattr(gl, n, X) 

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

496 X[n] = v 

497 return X 

498 

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

500 '''(INTERNAL) Remove superfluous items. 

501 ''' 

502 for k, C in _key2Caps.items(): 

503 if k in self and (outmask & C) != C: 

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

505 return self 

506 

507 

508class GeodSolve12Tuple(_GTuple): 

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

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

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

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

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

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

515 ''' 

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

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

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

519 

520 

521class Inverse10Tuple(_GTuple): 

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

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

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

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

526 ''' 

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

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

529 

530 def toGDict(self, **updates): 

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

532 

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

534 ''' 

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

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

537 **updates) # PYCHOK indent 

538 

539 

540class _kWrapped(object): # in .geodesicw 

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

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

543 ''' 

544 

545 @property_ROnce 

546 def geographiclib(self): 

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

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

549 otherwise raise a C{LazyImportError}. 

550 ''' 

551 g = _xgeographiclib(self.__class__.__module__, 1, 49) 

552 from geographiclib.geodesic import Geodesic 

553 g.Geodesic = Geodesic 

554 from geographiclib.geodesicline import GeodesicLine 

555 g.GeodesicLine = GeodesicLine 

556 from geographiclib.geomath import Math 

557 g.Math = Math 

558 return g 

559 

560 @property_ROnce 

561 def Math(self): 

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

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

564 otherwise C{None}. 

565 ''' 

566 try: 

567 g = self.geographiclib 

568 M = g.Math 

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

570 if _K_2_0: 

571 M = None 

572# elif not _K_2_0: # XXX set 2.0? 

573# _K_2_0 = True 

574 except (AttributeError, ImportError): 

575 M = None 

576 return M 

577 

578 @property_RO 

579 def Math_K_2(self): 

580 return (_2_4_ if _K_2_4 else 

581 (_2_ if _K_2_0 else _1_)) if self.Math else NN 

582 

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

584 

585 

586class Rhumb8Tuple(_GTuple): 

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

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

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

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

591 ''' 

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

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

594 

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

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

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

598 

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

600 @kwarg a12_azi1_azi2_m12_M12_M21: Optional keyword arguments 

601 to specify or override L{Inverse10Tuple} items. 

602 

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

604 m12, M12, M21, S12)} 

605 ''' 

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

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

608 if a12_azi1_azi2_m12_M12_M21: 

609 d.update(a12_azi1_azi2_m12_M12_M21) 

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

611 

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

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

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

615 

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

617 @kwarg a12_m12_M12_M21_salp1_calp1_salp2_calp2: Optional keyword 

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

619 

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

621 m12, M12, M21, S12)}. 

622 ''' 

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

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

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

626 if a12_m12_M12_M21_salp1_calp1_salp2_calp2: 

627 d.update(a12_m12_M12_M21_salp1_calp1_salp2_calp2) 

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

629 

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

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

632 ''' 

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

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

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

636 

637 @deprecated_method 

638 def _to7Tuple(self): 

639 '''DEPRECATED, do not use!''' 

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

641 

642 

643class _Xables(object): 

644 '''(INTERNAL) Get I{Karney}'s executable paths from/and env vars. 

645 ''' 

646 bin_ = '/opt/local/bin/' # '/opt/local/Cellar/geographiclib/2.3/bin/' # HomeBrew on macOS 

647 ENV = NN 

648 

649 def GeoConvert(self, *dir_): 

650 return self._path(self.GeoConvert, *dir_) 

651 

652 def GeodSolve(self, *dir_): 

653 return self._path(self.GeodSolve, *dir_) 

654 

655 def IntersectTool(self, *dir_): 

656 return self._path(self.IntersectTool, *dir_) 

657 

658 def RhumbSolve(self, *dir_): 

659 return self._path(self.RhumbSolve, *dir_) 

660 

661 def name_version(self, path, base=True): 

662 # return C{(path + ' ' + version)} of an executable 

663 if path: 

664 try: 

665 r, s = _popen2((path, '--version')) 

666 if base: 

667 path = _MODS.os.path.basename(path) 

668 r = _SPACE_(path, r.split()[-1]) 

669 else: 

670 r = _MODS.streprs.Fmt.PARENSPACED(r, s) 

671 return r 

672 except (IndexError, IOError, OSError): 

673 pass 

674 return NN 

675 

676 def _path(self, which, *dir_): 

677 self.ENV = E = _PYGEODESY(which) 

678 return _getenv(E, NN) or \ 

679 (NN(dir_[0], which.__name__) if dir_ else E) 

680 

681 def X_not(self, path): 

682 return 'env %s=%r not executable' % (self.ENV, path) 

683 

684 def X_OK(self, path): # is C{path} an executable? 

685 os = _MODS.os # import os 

686 return os.access(path, os.X_OK) if path else False 

687 

688_Xables = _Xables() # PYCHOK singleton 

689 

690 

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

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

693 

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

695 

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

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

698 ''' 

699 try: 

700 return _wrapped.Math.AngRound(x) 

701 except AttributeError: 

702 if x: 

703 y = _1_16th - fabs(x) 

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

705 x = _copysign(_1_16th - y, x) 

706 else: 

707 x = _0_0 # -0 to 0 

708 return x 

709 

710 

711def _atan2d(y, x): 

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

713 ''' 

714 try: 

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

716 except AttributeError: 

717 return atan2d(y, x) 

718 

719 

720def _cbrt(x): 

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

722 ''' 

723 try: 

724 return _wrapped.Math.cbrt(x) 

725 except AttributeError: 

726 return cbrt(x) 

727 

728 

729def _copyBit(x, y): 

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

731 ''' 

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

733 

734 

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

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

737 ''' 

738 r = cx - sx 

739 if r: 

740 r *= (cx + sx) * _2_0 

741 return r 

742 

743 

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

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

746 

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

748 ''' 

749 try: 

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

751 except AttributeError: 

752 if K_2_0 or _K_2_0: # geographiclib 2.0 

753 _r, _360 = fremainder, _360_0 

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

755 _r( deg, _360)) 

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

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

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

759 else: 

760 _n = _norm180 

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

762 d = _n(d) 

763 if t > 0 and d == _180_0: 

764 d = _N_180_0 

765 d, t = _sum2(d, t) 

766 return d, t 

767 

768 

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

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

771 

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

773 ''' 

774 try: 

775 return _wrapped.Math.LatFix(deg) 

776 except AttributeError: 

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

778 

779 

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

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

782 

783 @return: C{True} if finite. 

784 ''' 

785 try: 

786 return _wrapped.Math.isfinite(x) 

787 except AttributeError: 

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

789 

790 

791def _llz2gl(gl, **llz2): # see .geodesici._llz2G 

792 '''(INTERNAL) Set C{gl.lat2, .lon2, .azi2} from C{llz2}. 

793 ''' 

794 if llz2: 

795 for n in (_lat2_, _lon2_, _azi2_): # _lat1_, _lon1_, _azi1_ 

796 v = llz2.get(n, None) 

797 if v is not None: 

798 setattr(gl, n, v) 

799 return gl 

800 

801 

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

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

804 

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

806 ''' 

807 try: 

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

809 except AttributeError: 

810 return norm2(x, y) 

811 

812 

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

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

815 

816 @return: Reduced angle C{degrees}. 

817 ''' 

818 try: 

819 return _wrapped.Math.AngNormalize(deg) 

820 except AttributeError: 

821 d = fremainder(deg, _360_0) 

822 if d in (_180_0, _N_180_0): 

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

824 return d 

825 

826 

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

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

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

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

831 or C{geodesicw.Geodesic} instance. 

832 ''' 

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

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

835 

836 if _MODS.booleans.isBoolean(points): 

837 # recursive call for each boolean clip 

838 

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

840 return _polygon(geodesic, clip, *args) 

841 

842 if not closed: # closed only 

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

844 

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

846 

847 gP = geodesic.Polygon(line) 

848 _A = gP.AddPoint 

849 

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

851 p1 = p0 = Ps[0] 

852 

853 # note, lon deltas are unrolled, by default 

854 _A(p1.lat, p1.lon) 

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

856 if wrap and not Ps.looped: 

857 p2 = _unrollon(p1, p2) 

858 _A(p2.lat, p2.lon) 

859 p1 = p2 

860 if closed and line and p1 != p0: 

861 _A(p0.lat, p0.lon) 

862 

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

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

865 

866 

867try: 

868 from math import fma as _fma # since 3.13 

869 

870 def _poly_fma(x, s, *cs): 

871 for c in cs: 

872 s = _fma(s, x, c) 

873 return s 

874 

875except ImportError: # Python 3.12- 

876 

877 def _poly_fma(x, s, *cs): # PYCHOK redef 

878 t = _0_0 

879 for c in cs: 

880 s, t, _ = _sum3(s * x, t * x, c) 

881 return s + t 

882 

883# def _poly_fma(x, s, *cs): 

884# S = Fhorner(x, *cs, incx=False) 

885# S += s 

886# return float(S) 

887 

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

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

890 signature and cascaded summation different from C{karney._sum3}. 

891 

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

893 ''' 

894 if (i + 1) < j <= len(cs): # load _Rtuple._tuple 

895 try: 

896 r = _wrapped.Math.polyval(j - i - 1, cs, i, x) 

897 except AttributeError: # no .Math 

898 r = _poly_fma(x, _0_0, *cs[i:j]) 

899 else: 

900 r = cs[i] 

901 return float(r) 

902 

903 

904def _remainder(x, y): 

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

906 

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

908 ''' 

909 try: 

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

911 except AttributeError: 

912 return fremainder(x, y) 

913 

914 

915if _K_2_0: 

916 from math import cos as _cos, sin as _sin 

917 

918 def _sincos2(rad): 

919 return _sin(rad), _cos(rad) 

920 

921 _signBit = _MODS.basics.signBit 

922else: 

923 _sincos2 = _MODS.utily.sincos2 # PYCHOK shared 

924 

925 def _signBit(x): 

926 '''(INTERNAL) GeographicLib 1.52-. 

927 ''' 

928 return x < 0 

929 

930 

931def _sincos2d(deg): 

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

933 

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

935 ''' 

936 try: 

937 return _wrapped.Math.sincosd(deg) 

938 except AttributeError: 

939 return sincos2d(deg) 

940 

941 

942def _sincos2de(deg, t): 

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

944 

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

946 ''' 

947 try: 

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

949 except AttributeError: 

950 return sincos2d(deg, adeg=t) 

951 

952 

953def _sum2(a, b): # mimick geomath.Math.sum, actually sum2 

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

955 

956 @return: 2-Tuple C{(B{a} + B{b}, residual)}. 

957 

958 @note: The C{residual} can be the same as B{C{a}} or B{C{b}}. 

959 

960 @see: U{TwoSum<https://accurate-algorithms.readthedocs.io/en/latest/ch04summation.html>} 

961 and I{Knuth}'s U{Algorithm 3.1<https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}. 

962 ''' 

963 try: 

964 return _wrapped.Math.sum(a, b) 

965 except AttributeError: 

966 # if Algorithm_3_1: 

967 s = a + b 

968 r = s - b 

969 t = s - r 

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

971 # r -= a; t -= b; t += r; t = -t 

972 # else: 

973 t = (a - r) + (b - t) 

974 # assert fabs(s) >= fabs(t) 

975 return s, t 

976 

977 

978def _sum3(s, t, *xs): 

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

980 

981 @return: 3-Tuple C{(s, t, n)} where C{s} is the sum of B{s}, B{t} and all 

982 B{xs}, C{t} the residual and C{n} the number of zero C{xs}. 

983 

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

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

986 function C{_sum2} above. 

987 

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

989 ''' 

990 z = 0 

991 for x in xs: 

992 if x: 

993 t, r = _sum2(t, x) # start at the least- 

994 if s: 

995 s, t = _sum2(s, t) # -significant end 

996 if s: 

997 t += r # accumulate r into t 

998 else: 

999 # assert t == 0 # s == 0 implies t == 0 

1000 s = unsigned0(r) # result is r, t = 0 

1001 else: 

1002 s, t = unsigned0(t), r 

1003 else: 

1004 z += 1 

1005 # assert fabs(s) >= fabs(t) 

1006 return s, t, z 

1007 

1008 

1009def _tand(x): 

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

1011 ''' 

1012 try: 

1013 return _wrapped.Math.tand(x) 

1014 except AttributeError: 

1015 return tand(x) # Error=None 

1016 

1017 

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

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

1020 

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

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

1023 ''' 

1024 if wrap: 

1025 d, t = _diff182(lon1, lon2) 

1026 lon2, t, _ = _sum3(d, t, lon1) # (lon1 + d) + t 

1027 lon2 += t 

1028 else: 

1029 lon2 = _norm180(lon2) 

1030 return (lon2 - lon1), lon2 

1031 

1032 

1033def _unsigned2(x): 

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

1035 ''' 

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

1037 

1038 

1039__all__ += _ALL_DOCS(_CapsBase) 

1040 

1041# **) MIT License 

1042# 

1043# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved. 

1044# 

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

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

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

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

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

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

1051# 

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

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

1054# 

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

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

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

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

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

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

1061# OTHER DEALINGS IN THE SOFTWARE.