Coverage for pygeodesy/geodesici.py: 91%

620 statements  

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

1 

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

3 

4u'''Classes L{Intersectool} and L{Intersector} to find the intersections of two geodesic lines or line segments. 

5 

6Class L{Intersector} is a pure Python version of I{Karney}'s C++ class U{Intersect 

7<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Intersect.html>}. 

8 

9Class L{Intersectool} is a wrapper to invoke I{Karney}'s U{IntersectTool 

10<https://GeographicLib.SourceForge.io/C++/doc/IntersectTool.1.html>} utility, but intended I{for testing purposes only}. 

11 

12Set env variable C{PYGEODESY_INTERSECTTOOL} to the (fully qualified) path of the C{IntersectTool} executable. For usage 

13and some examples run C{"env PYGEODESY_INTERSECTTOOL=<IntersectTool-path> python3 -m pygeodesy.geodesici --help"}. 

14 

15Both L{Intersectool} and L{Intersector} provide methods C{All}, C{Closest}, C{Next} and C{Segment} and produce 

16L{XDict} instances with 4 or more items. Adjacent methods C{All5}, C{Closest5}, C{Next5} and C{Segment} return 

17or yield L{Intersectool5Tuple} or L{Intersector5Tuple}s with the lat-, longitude and azimuth of each intersection 

18as an extended, geodesic C{Position}-like L{GDict} instance. 

19 

20For more details, see the C++ U{GeographicLib<https://GeographicLib.SourceForge.io/C++/doc/index.html>} 

21documentation, I{Charles F.F. Karney}'s paper U{Geodesics intersections<https://arxiv.org/abs/2308.00495>} 

22and I{S. Baselga Moreno & J.C. Martinez-Llario}'s U{Intersection and point-to-line solutions for geodesics 

23on the ellipsoid<https://riunet.UPV.ES/bitstream/handle/10251/122902/Revised_Manuscript.pdf>}. 

24''' 

25# make sure int/int division yields float quotient 

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

27 

28from pygeodesy.basics import _copy, _enumereverse, map1, \ 

29 _xinstanceof, _xor 

30from pygeodesy.constants import EPS, INF, INT0, PI, PI2, PI_4, \ 

31 _0_0, _0_5, _1_0, _1_5, _2_0, _3_0, \ 

32 _45_0, _64_0, _90_0, isfinite, \ 

33 _EPSjam # PYCHOK used! 

34from pygeodesy.ellipsoids import _EWGS84, Fmt, unstr 

35from pygeodesy.errors import GeodesicError, IntersectionError, _an, \ 

36 _xgeodesics, _xkwds_get, _xkwds_kwds, \ 

37 _xkwds_pop2 

38# from pygeodesy.errors import exception_chaining # _MODS 

39from pygeodesy.fmath import euclid, fdot 

40from pygeodesy.fsums import Fsum, fsum1_, _ceil 

41from pygeodesy.interns import NN, _A_, _B_, _c_, _COMMASPACE_, _HASH_, \ 

42 _M_, _not_, _SPACE_, _too_ 

43from pygeodesy.karney import Caps, _diff182, GDict, _sincos2de, _Xables 

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

45from pygeodesy.named import ADict, _NamedBase, _NamedTuple, _Pass 

46# from pygeodesy.namedTuples import _LL4Tuple # _MODS 

47from pygeodesy.props import deprecated_method, Property, \ 

48 Property_RO, property_RO, property_ROver 

49from pygeodesy.solveBase import _SolveCapsBase, pairs 

50# from pygeodesy.streprs import pairs # from .solveBase 

51# from pygeodesy.streprs import Fmt, unstr # from .ellipsoids 

52from pygeodesy.units import Azimuth as Azi, Degrees, Float, Int, \ 

53 _isDegrees, Lat, Lon, Meter, Meter_ 

54from pygeodesy.utily import atan2, sincos2, fabs, radians 

55 

56# from math import ceil as _ceil, fabs, radians # .fsums, .utily 

57 

58__all__ = _ALL_LAZY.geodesici 

59__version__ = '24.12.22' 

60 

61_0t = 0, # int 

62_1_1t = -1, +1 

63_1_0_1t = -1, 0, +1 

64_aAB_ = 'aAB' 

65_c__ = '-c' # PYCHOK used! 

66_cWGS84 = _EWGS84.a * PI2 # outer circumference 

67_EPS3 = EPS * _3_0 

68_EPSr5 = pow(EPS, 0.2) # PYCHOK used! 7.4e-4 or ~3" 

69_i__ = '-i' # PYCHOK used! 

70_latA_ = 'latA' 

71_lonA_ = 'lonA' 

72_n__ = '-n' # PYCHOK used! 

73_o__ = '-o' # PYCHOK used! 

74_R__ = '-R' 

75_sAB_ = 'sAB' 

76_sX0_ = 'sX0' 

77_TRIPS = 128 

78 

79 

80class XDict(ADict): 

81 '''4+Item result from L{Intersectool} and L{Intersector} methods 

82 C{All}, C{Closest}, C{Next} and C{Segment} with the intersection 

83 offsets C{sA}, C{sB} and C{sX0} in C{meter} and the coincidence 

84 indicator C{c}, an C{int}, +1 for parallel, -1 for anti-parallel 

85 or 0 otherwise. 

86 

87 Offsets C{sA} and C{sB} are distances measured I{along} geodesic 

88 line C{glA} respectively C{glB}, but C{sX0} is the I{L1-distance} 

89 between the intersection and the I{origin} C{X0}. 

90 

91 If present, distance C{sAB} and angular distance C{aAB} represent 

92 the difference between the intersection point on geodesic lines 

93 C{glA} and C{glB} in C{meter} respectively C{degrees}, typically 

94 below C{5e-9 meter} or C{5 nm} and C{5e-14 degrees} or C{1 n"}. 

95 

96 For segments, indicators C{kA} and C{kB} are C{0} if the segments 

97 intersect or C{-1} or C{+1} if the intersection is I{before} the 

98 start, respectively I{after} the end of the segment, similar to 

99 L{Intersection3Tuple<Intersection3Tuple>}. Segment indicator 

100 C{k} is I{Karney}'s C{segmode}, equal C{kA * 3 + kB}. 

101 ''' 

102 _Delta = EPS # default margin, see C{Intersector._Delto} 

103 

104 def __add__(self, other): 

105 X = _copy(self) 

106 X += other 

107 return X 

108 

109 def __eq__(self, other): 

110 return not self.__ne__(other) 

111 

112 def __iadd__(self, other): 

113 if isinstance(other, tuple): # and len(other) == 2: 

114 a, b = other 

115 else: 

116 # _xinstanceof(XDict, other=other) 

117 a = other.sA 

118 b = other.sB 

119 if other.c: 

120 self.c = other.c 

121 self.sA += a # PYCHOK sA 

122 self.sB += b # PYCHOK sB 

123 return self 

124 

125 def __le__(self, other): 

126 # _xinstanceof(XDict, other=other) 

127 return self == other or self < other 

128 

129 def __lt__(self, other): 

130 # _xinstanceof(XDict, other=other) 

131 return (self.sA < other.sA or (self.sA == other.sA and # PYCHOK sA 

132 self.sB < other.sB) and self != other) # PYCHOK sB 

133 

134 def __ne__(self, other): 

135 # _xinstanceof(XDict, other=other) 

136 return self is not other and self.L1(other) > self._Delta 

137 

138 def _corners(self, sA, sB, T2): 

139 # yield all corners further than C{T2} 

140 a, b = self.sA, self.sB # PYCHOK sA, sB 

141 for x in (0, sA): 

142 for y in (0, sB): 

143 if _L1(x - a, y - b) >= T2: 

144 yield XDict_(x, y) 

145 

146 def _fixCoincident(self, X, c0=0): 

147 # return the mid-point if C{X} is anti-/parallel 

148 c = c0 or X.c 

149 if c: 

150 s = (self.sA - X.sA + # PYCHOK sA 

151 (self.sB - X.sB) * c) * _0_5 # PYCHOK sB 

152 X = X + (s, s * c) # NOT += 

153 return X 

154 

155 def _fixSegment(self, sA, sB): # PYCHOK no cover 

156 # modify this anti-/parallel C{XDict} 

157 a, b, c = self.sA, self.sB, self.c # PYCHOK sA, sB, c 

158 

159 def _g(): # intersection in smallest gap 

160 if c > 0: # distance to [A, B] is |(a - b) - (A - B)| 

161 t = a - b # consider corners [0, sB] and [sA, 0] 

162 t = fabs(t + sB) < fabs(t - sA) 

163 s = a + b 

164 else: # distance to [A, B] is |(a + b) - (A + B)| 

165 t = a + b # consider corner [0, 0] and [sA, sB] 

166 t = fabs(t) < fabs(t - (sA + sB)) 

167 s = sB + (a - b) 

168 return (sB if t else sA) - s 

169 

170 ta = -a 

171 tb = sA - a 

172 tc = -c * b 

173 td = -c * (b - sB) 

174 

175 ga = 0 <= (b + c * ta) <= sB 

176 gb = 0 <= (b + c * tb) <= sB 

177 gc = 0 <= (a + tc) <= sA 

178 gd = 0 <= (a + td) <= sA 

179 

180 # test opposite rectangle sides first 

181 s = ((ta + tb) if ga and gb else ( 

182 (tc + td) if gc and gd else ( 

183 (ta + tc) if ga and gc else ( 

184 (ta + td) if ga and gd else ( 

185 (tb + tc) if gb and gc else ( 

186 (tb + td) if gb and gd else _g())))))) * _0_5 

187 self += s, s * c 

188 

189 @property_RO 

190 def _is00(self): 

191 return not (self.sA or self.sB) # PYCHOK sA, sB 

192 

193 def L1(self, other=None): 

194 '''Return the C{L1} distance. 

195 ''' 

196 a, b = self.sA, self.sB # PYCHOK sA, sB 

197 if other is not None: 

198 # _xinstanceof(XDict, other=other) 

199 a -= other.sA 

200 b -= other.sB 

201 return _L1(a, b) 

202 

203 def _nD1(self, D1): 

204 # yield the C{Closest} starts 

205 D_ = 0, D1, -D1 

206 for a, b in zip((0, 1, -1, 0, 0), 

207 (0, 0, 0, 1, -1)): 

208 yield self + (D_[a], D_[b]) 

209 

210 def _nD2(self, D2): 

211 # yield the C{Next} starts 

212 D22 = D2 * _2_0 

213 D_ = 0, D2, D22, -D22, -D2 

214 for a, b in zip((-1, -1, 1, 1, -2, 0, 2, 0), 

215 (-1, 1, -1, 1, 0, 2, 0, -2)): 

216 yield self + (D_[a], D_[b]) 

217 

218 def _nmD3(self, n, m, D3): # d3 / 2 

219 # yield the C{All} starts 

220 yield self 

221 for i in range(n, m, 2): 

222 for j in range(n, m, 2): 

223 if i or j: # skip self 

224 yield self + ((i + j) * D3, 

225 (i - j) * D3) 

226 

227 def _outSide(self, sA, sB): 

228 # is this C{Xdist} outside one or both segments? 

229 a, b = self.sA, self.sB # PYCHOK sA, sB 

230 kA = -1 if a < 0 else (+1 if a > sA else INT0) 

231 kB = -1 if b < 0 else (+1 if b > sB else INT0) 

232 self.set_(kA=kA, kB=kB, k=(kA * 3 + kB) or INT0) 

233 return bool(kA or kB) 

234 

235 def _skip(self, S_, T1_Delta): 

236 # remove starts from list C{S_} near this C{XDict} 

237 for j, S in _enumereverse(S_): 

238 if S.L1(self) < T1_Delta: 

239 S_.pop(j) 

240 

241 

242def XDict_(sA=_0_0, sB=_0_0, c=INT0, sX0=_0_0): 

243 '''(INTERNAL) New L{XDict} from positionals. 

244 ''' 

245 return XDict(sA=sA, sB=sB, c=c, sX0=sX0) 

246 

247_X000 = XDict_() # PYCHOK origin 

248_XINF = XDict_(INF) 

249 

250 

251class _IntersectBase(_NamedBase): 

252 '''(INTERNAL) Base class for L{Intersectool} and L{Intersector}. 

253 ''' 

254 # _g = None 

255 

256 def __init__(self, geodesic, **name): 

257 _xinstanceof(*_EWGS84._Geodesics, geodesic=geodesic) 

258 self._g = geodesic 

259 if name: 

260 self.name = name 

261 

262 @Property_RO 

263 def a(self): 

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

265 ''' 

266 return self.ellipsoid.a 

267 

268 equatoradius = a # = Requatorial 

269 

270 def All(self, glA, glB, **kwds): # PYCHOK no cover 

271 '''(INTERNAL) I{Must be overloaded}.''' 

272 self._notOverloaded(glA, glB, **kwds) 

273 

274 @Property_RO 

275 def _cHalf(self): # normalizer, semi-circumference 

276 return self.R * PI # ~20K Km WGS84 

277 

278 @Property_RO 

279 def _cMax(self): # outer circumference 

280 return max(self.a, self.ellipsoid.b, self.R) * PI2 

281 

282 @property_RO 

283 def datum(self): 

284 '''Get the geodesic's datum (C{Datum}). 

285 ''' 

286 return self.geodesic.datum 

287 

288 @Property_RO 

289 def ellipsoid(self): 

290 '''Get the C{geodesic}'s ellipsoid (C{Ellipsoid}). 

291 ''' 

292 return self.geodesic.datum.ellipsoid 

293 

294 @Property_RO 

295 def f(self): 

296 '''Get the I{flattening} (C{scalar}), C{0} for spherical, negative for prolate. 

297 ''' 

298 return self.ellipsoid.f 

299 

300 flattening = f 

301 

302 @property_RO 

303 def geodesic(self): 

304 '''Get the C{geodesic} (C{Geodesic...}). 

305 ''' 

306 return self._g 

307 

308 def _illz2G(self, G, il): 

309 '''(INTERNAL) Set C{InverseLine} 1-/2-attrs into C{G}, a C{GDict}. 

310 ''' 

311 try: 

312 G.set_(lat1=il.lat1, lon1=il.lon1, azi1=il.azi1, a12=il.a13, # .Arc() 

313 lat2=il.lat2, lon2=il.lon2, azi2=il.azi2, s12=il.s13) # .Distance() 

314 except AttributeError: 

315 r = il.Position(il.s13, outmask=Caps._STD_LINE) # isfinite(il.s13) 

316 G.set_(**r) 

317# for n, v in r.items(): 

318# if not hasattr(il, n): 

319# setattr(il, n, v) 

320 return G 

321 

322 def intersect7(self, start1, end1, start2, end2, X0=_X000, aMaX0=0, sMaX0=_cWGS84, 

323 **LatLon_and_kwds): 

324 '''Yield the intersection points of two lines, each defined by two (ellipsoidal) 

325 points or by an (ellipsoidal) start point and an azimuth from North. 

326 

327 @arg start1: Start point of the first line (C{LatLon}). 

328 @arg end1: End point of the first line (C{LatLon}) or the azimuth at the 

329 B{C{start1}} point (compass C{degrees360}). 

330 @arg start2: Start point of the second line (C{LatLon}). 

331 @arg end2: End point of the second line (C{LatLon}) or the azimuth at the 

332 B{C{start2}} point (compass C{degrees360}). 

333 @kwarg X0: Optional I{origin} for I{L1-distances} (L{XDict}) or C{None} for 

334 the L{Middle<Intersector.Middle>}, otherwise C{XDiff_(0, 0)}. 

335 @kwarg aMaX0: Upper limit for the I{angular L1-distance} 

336 (C{degrees}) or C{None} or C{0} for unlimited. 

337 @kwarg sMaX0_C: Optional, upper limit C{B{sMaX0}=2*PI*R} for the 

338 I{L1-distance} to B{C{X0}} (C{meter}). 

339 @kwarg LatLon_and_kwds: Optional class C{B{LatLon}=None} to return intersection 

340 points and optional, additional B{C{LatLon}} keyword arguments. 

341 

342 @note: The C{lat} and C{lon} attr of B{C{start1}}, B{C{end1}}, B{C{start2}} and 

343 B{C{end2}} are used I{verbatim}, ignoring C{datum} or C{ellipsoid}. 

344 

345 @return: Yield an L{Intersect7Tuple}C{(A, B, sAB, aAB, c, kA, kB)} for every 

346 intersection found, with C{A} and C{B} each a B{C{LatLon}} or if 

347 C{B{LatLon} is None} or not specified, a L{LatLon4Tuple}C{(lat, lon, 

348 height, datum)} with C{height 0} and this C{datum}. 

349 

350 @raise GeodesicError: Invalid B{C{start1}}, B{C{end1}}, B{C{start2}} or 

351 B{C{end2}} or B{C{end1}} and B{C{end2}} differ in type. 

352 

353 @raise IntersectionError: No convergence. 

354 ''' 

355 

356 def _args(s, e): 

357 t = (e,) if _isDegrees(e) else (e.lat, e.lon) 

358 return (s.lat, s.lon) + t 

359 

360 try: 

361 glA = self.Line(*_args(start1, end1)) 

362 glB = self.Line(*_args(start2, end2)) 

363 except Exception as x: 

364 raise GeodesicError(start1=start1, end1=end1, start2=start2, end2=end2, cause=x) 

365 

366 LL, kwds = _xkwds_pop2(LatLon_and_kwds, LatLon=None) 

367 d, kwds = _xkwds_pop2(kwds, datum=self.datum) 

368 h, kwds = _xkwds_pop2(kwds, height=0) 

369 

370 _LL4T = _MODS.namedTuples._LL4Tuple 

371 for X in self.All(glA, glB, X0=X0, aMaX0=aMaX0, sMaX0=sMaX0, _C=True): 

372 A = B = _LL4T(X.latA, X.lonA, h, d, LL, kwds, iteration=X.iteration) 

373 if X.sAB or X.latA != X.latB or X.lonA != X.lonB: 

374 B = _LL4T(X.latB, X.lonB, h, d, LL, kwds, iteration=X.iteration) 

375 yield Intersect7Tuple(A, B, X.sAB, X.aAB, X.c, _xkwds_get(X, kA=0), 

376 _xkwds_get(X, kB=0)) 

377 

378 def _Inversa12(self, A, B=None): 

379 lls = (0, 0, A, 0) if B is None else (A.lat2, A.lon2, 

380 B.lat2, B.lon2) 

381 r = self._g.Inverse(*lls, outmask=Caps.DISTANCE) 

382 return r.s12, r.a12 # .a12 always in r 

383 

384 def k2kAkB(self, k): 

385 '''Unravel C{k} into C{kA} and C{kB}. 

386 

387 @arg k: Segment indicator C{kA * 3 + kB} (C{int}). 

388 

389 @return: An C{ADict(k=k, kA=kA, kB=kB)}. 

390 

391 @raise GeodesicError: Invalid B{C{k}}. 

392 ''' 

393 for kA in range(-1, 2): 

394 for kB in range(-1, 2): 

395 if (kA * 3 + kB) == k: 

396 return ADict(k=k, kA=kA, kB=kB) 

397 raise GeodesicError(k=k) 

398 

399# def k2kAkB(self, k): 

400# # unravel C{k} into C{kA} and C{kB}. 

401# kA, kB = divmod(k, 3) 

402# if kB > 1: 

403# kA += 1 

404# kB -= 3 

405# return kA, kB 

406 

407 def Line(self, lat1, lon1, azi1_lat2, *lon2, **name): # PYCHOK no cover 

408 '''(INTERNAL) I{Must be overloaded}.''' 

409 self._notOverloaded(lat1, lon1, azi1_lat2, *lon2, **name) 

410 

411 def _ll3z4ll(self, lat1, lon1, azi1_lat2, *lon2): 

412 t = Lat(lat1=lat1), Lon(lon1=lon1) 

413 if lon2: # get azis for All, keep lat-/lons 

414 t += Lat(lat2=azi1_lat2), Lon(lon2=lon2[0]) 

415 else: 

416 t += Azi(azi1=azi1_lat2), 

417 return t 

418 

419 @deprecated_method 

420 def Next5s(self, glA, glB, X0=_X000, aMax=1801, sMax=0, **unused): # PYCHOK no cover 

421 '''DEPRECATED on 2024.07.02, use method C{All5}.''' 

422 return self.All5(glA, glB, X0=X0, aMaX0=aMax, sMaX0=sMax) # PYCHOK attr 

423 

424 @Property_RO 

425 def R(self): 

426 '''Get the I{authalic} earth radius (C{meter}). 

427 ''' 

428 return self.ellipsoid.R2 

429 

430 def _sMaX0_C2(self, aMaX0=0, **sMaX0_C): 

431 _g = _xkwds_get 

432 s = _g(sMaX0_C, sMaX0=self._cMax) 

433 s = _g(sMaX0_C, sMax=s) # for backward ... 

434 a = _g(sMaX0_C, aMax=aMaX0) # ... compatibility 

435 if a: # degrees to meter, approx. 

436 s = min(s, self.R * radians(a)) # ellipsoid.degrees2m(a) 

437 s = _g(sMaX0_C, _R=s) 

438 if s < _EPS3: 

439 s = _EPS3 # raise GeodesicError(sMaX0=s) 

440 return s, _g(sMaX0_C, _C=False) 

441 

442 def _xNext(self, glA, glB, eps1, **eps_C): # PYCHOK no cover 

443 eps1 = _xkwds_get(eps_C, eps=eps1) # eps for backward compatibility 

444 if eps1 is not None: 

445 a = glA.lat1 - glB.lat1 

446 b = glA.lon1 - glB.lon1 

447 if euclid(a, b) > eps1: 

448 raise GeodesicError(lat_=a, lon_=b, eps1=eps1) 

449 return _xkwds_kwds(eps_C, _C=False) 

450 

451 

452class Intersectool(_IntersectBase, _SolveCapsBase): 

453 '''Wrapper to invoke I{Karney}'s utility U{IntersectTool 

454 <https://GeographicLib.SourceForge.io/C++/doc/IntersectTool.1.html>} 

455 similar to class L{Intersector<geodesici.Intersector>}. 

456 

457 @note: Use property C{IntersectTool} or env variable C{PYGEODESY_INTERSECTTOOL} 

458 to specify the (fully qualified) path to the C{IntersectTool} executable. 

459 

460 @note: This C{Intersectool} is intended I{for testing purposes only}, it invokes 

461 the C{IntersectTool} executable for I{every} method call. 

462 ''' 

463 _c_alt = _c__, # Closest latA lonA aziA latB lonB aziB 

464 _C_option = '-C', 

465 _Error = GeodesicError 

466 _i_alt = _i__, # Segment latA1 lonA1 latA2 lonA2 latB1 lonB1 latB2 lonB2 

467 _linelimit = 1200 # line printer width X 10 

468 _n_alt = _n__, # Next latA lonA aziA aziB 

469 _Names_ABs = _latA_, _lonA_, 'latB', 'lonB', _sAB_ # -C to stderr 

470 _Names_XDict = 'sA', 'sB', _c_ # plus 'k' from -i or 'sX0' from -R 

471 _o_alt = _o__, # Offset latA lonA aziA latB lonB aziB x0 y0 

472 _Xable_name = _Xables.IntersectTool.__name__ 

473 _Xable_path = _Xables.IntersectTool() 

474 

475 def __init__(self, a_geodesic=None, f=None, **name): 

476 '''New L{IntersectTool}. 

477 

478 @arg a_geodesic: Earth' equatorial axis (C{meter}) or a geodesic 

479 (L{GeodesicExact<pygeodesy.geodesicx.GeodesicExact>}, 

480 wrapped L{Geodesic<pygeodesy.geodesicw.Geodesic>} or 

481 L{GeodesicSolve<pygeodesy.geodsolve.GeodesicSolve>}). 

482 @kwarg f: Earth' flattening (C{scalar}), required if B{C{a_geodesic}} 

483 is in C{meter}, ignored otherwise. 

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

485 

486 @raise GeodesicError: The eccentricity of the B{C{geodesic}}'s ellipsoid is too 

487 large or no initial convergence. 

488 

489 @see: The B{Note} at I{Karney}'s C++ U{Intersect<https://GeographicLib.sourceforge.io/ 

490 C++/doc/classGeographicLib_1_1Intersect.html#ae41f54c9a44836f6c8f140f6994930cf>}. 

491 ''' 

492 g = self._GeodesicExact() if a_geodesic is None else (a_geodesic if f is None else 

493 self._GeodesicExact(a_geodesic, f)) 

494 _IntersectBase.__init__(self, g, **name) 

495 

496 def All(self, glA, glB, X0=_X000, eps1=_0_0, aMaX0=0, **sMaX0_C): # PYCHOK signature 

497 '''Yield all intersection of two geodesic lines up to a limit. 

498 

499 @kwarg eps1: Optional margin for the L{euclid<pygeodesy.euclid>}ean distance 

500 (C{degrees}) between the C{(lat1, lon1)} points of both lines for 

501 using the L{IntersectTool<Intersectool.IntersectTool>}'s C{"-n"} 

502 option, unless C{B{eps1}=None}. 

503 

504 @return: An L{XDict} for each intersection. 

505 ''' 

506 for X, _ in self._All2(glA, glB, X0, eps1, aMaX0=aMaX0, **sMaX0_C): 

507 yield X 

508 

509 def _All2(self, glA, glB, X0, eps1, **aMaX0_sMaX0_C): # MCCABE 13 

510 '''(INTERNAL) Helper for methods C{.All} and C{.All5}. 

511 ''' 

512 def _xz2(**gl): 

513 try: 

514 n, gl = gl.popitem() # _xkwds_item2(gl) 

515 try: 

516 return self._c_alt, (gl.azi1,) 

517 except (AttributeError, KeyError): 

518 return self._i_alt, (gl.lat2, gl.lon2) 

519 except Exception as x: 

520 raise GeodesicError(n, gl, cause=x) 

521 

522 _t, a = _xz2(glA=glA) 

523 _x, b = _xz2(glB=glB) 

524 if _x is not _t: 

525 raise GeodesicError(glA=glA, glB=glB) 

526 

527 A = glA.lat1, glA.lon1 

528 B = glB.lat1, glB.lon1 

529 if _x is self._c_alt: 

530 if X0 is _X000 or X0._is00: 

531 if eps1 is not None and \ 

532 euclid(glA.lat1 - glB.lat1, 

533 glA.lon1 - glB.lon1) <= eps1: 

534 _x, B = self._n_alt, () 

535 else: # non-zero offset 

536 _x = self._o_alt 

537 b += X0.sA, X0.sB 

538 

539 sMaX0, _C = self._sMaX0_C2(**aMaX0_sMaX0_C) 

540 for X in self._XDictInvoke(_x, _sX0_, (A + a + B + b), 

541 _C=_C, _R=sMaX0): 

542 if _C: 

543 T = self._In5T(glA, glB, X, X) 

544 if _aAB_ not in X: 

545 X.set_(sAB=T.sAB, aAB=T.aAB) 

546 else: 

547 T = None 

548 yield X.set_(c=int(X.c)), T 

549 

550 def All5(self, glA, glB, X0=_X000, **aMaX0_sMaX0): 

551 '''Yield all intersection of two geodesic lines up to a limit. 

552 

553 @return: An L{Intersectool5Tuple} for each intersection. 

554 ''' 

555 for _, T in self._All2(glA, glB, X0, _0_0, _C=True, **aMaX0_sMaX0): 

556 yield T 

557 

558 @Property_RO 

559 def _cmdBasic(self): 

560 '''(INTERNAL) Get the basic C{IntersectTool} cmd (C{tuple}). 

561 ''' 

562 return (self.IntersectTool,) + (self._e_option + 

563 self._E_option + 

564 self._p_option) 

565 

566 def Closest(self, glA, glB, X0=_X000, _C=False): 

567 '''Find the closest intersection of two geodesic lines. 

568 

569 @kwarg _C: Use C{B{_C}=True} to include the C{"-C"} results (C{bool}). 

570 

571 @return: An L{XDict}. 

572 ''' 

573 args = glA.lat1, glA.lon1, glA.azi1, \ 

574 glB.lat1, glB.lon1, glB.azi1 

575 if X0 is _X000 or X0._is000: 

576 _x = self._c_alt 

577 else: 

578 _x = self._o_alt 

579 args += X0.sA, X0.sB 

580 return self._XDictInvoke(_x, NN, args, _C=_C) # _R=None) 

581 

582 def Closest5(self, glA, glB, **unused): 

583 '''Find the closest intersection of two geodesic lines. 

584 

585 @return: An L{Intersectool5Tuple}. 

586 ''' 

587 X = self.Closest(glA, glB, _C=True) 

588 return self._In5T(glA, glB, X, X) 

589 

590 @property_ROver 

591 def _GeodesicExact(self): 

592 '''Get the I{class} L{GeodesicExact}, I{once}. 

593 ''' 

594 return _MODS.geodesicx.GeodesicExact # overwrite property_ROver 

595 

596 def _In5T(self, glA, glB, S, X, k2=False, **_2X): 

597 A = GDict(glA).set_(lat2=X.latA, lon2=X.lonA, s12=S.sA) 

598 B = GDict(glB).set_(lat2=X.latB, lon2=X.lonB, s12=S.sB) 

599 if k2: 

600 A.set_(k2=X.kA) 

601 B.set_(k2=X.kB) 

602 s, a = self._Inversa12(A, B) 

603 sAB = _xkwds_get(X, sAB=s) 

604 if a and s and s != sAB: 

605 a *= sAB / s # adjust a 

606 return Intersectool5Tuple(A._2X(glA, **_2X), 

607 B._2X(glB, **_2X), sAB, a, X.c) 

608 

609 @Property 

610 def IntersectTool(self): 

611 '''Get the U{IntersectTool<https://GeographicLib.SourceForge.io/C++/doc/IntersectTool.1.html>} 

612 executable (C{filename}). 

613 ''' 

614 return self._Xable_path 

615 

616 @IntersectTool.setter # PYCHOK setter! 

617 def IntersectTool(self, path): 

618 '''Set the U{IntersectTool<https://GeographicLib.SourceForge.io/C++/doc/IntersectTool.1.html>} 

619 executable (C{filename}), the (fully qualified) path to the C{IntersectTool} executable. 

620 

621 @raise GeodesicError: Invalid B{C{path}}, B{C{path}} doesn't exist or isn't the 

622 C{IntersectTool} executable. 

623 ''' 

624 self._setXable(path) 

625 

626 def Line(self, lat1, lon1, azi1_lat2, *lon2, **name): 

627 '''Return a geodesic line from this C{Intersector}'s geodesic, specified by 

628 two (goedetic) points or a (goedetic) point and an (forward) azimuth. 

629 

630 @return: A 3- or 6-item, named L{GDict}. 

631 ''' 

632 args = self._ll3z4ll(lat1, lon1, azi1_lat2, *lon2) 

633 gl = GDict((u.name, u) for u in args) 

634# if lon2: # get azis for All, use lat-/lons as given 

635# r = self._g.Inverse(outmask=Caps.AZIMUTH, *args) 

636# gl.set_(azi1=Azi(azi1=r.azi1), azi2=Azi(azi2=r.azi2)) 

637 if name: 

638 gl.name= name 

639 return gl 

640 

641 def Middle(self, glA, glB, **_C): 

642 '''Get the mid-points on two geodesic line segments. 

643 

644 @kwarg _C: Use C{B{_C}=True} to include the C{"-C"} results (C{bool}). 

645 

646 @return: An L{XDict}. 

647 ''' 

648 X, _, _, _, _ = self._middle5(glA, glB, **_C) 

649 return X 

650 

651 def _middle5(self, glA, glB, _C=False, **unused): 

652 # return intersections C{A} and C{B} and the 

653 # center C{X0} of rectangle [sA, sB] 

654 

655 def _smi4(**gl): 

656 try: 

657 n, gl = gl.popitem() 

658 il = self._g.InverseLine(gl.lat1, gl.lon1, gl.lat2, gl.lon2) 

659 except Exception as x: 

660 raise GeodesicError(n, gl, cause=x) 

661 s = il.s13 

662 m = s * _0_5 

663 return s, m, il, (il.Position(m, outmask=Caps._STD_LINE) if _C else None) 

664 

665 sA, mA, iA, A = _smi4(glA=glA) 

666 sB, mB, iB, B = _smi4(glB=glB) 

667 X = XDict_(mA, mB) # centers 

668 _ = X._outSide(sA, sB) 

669 if _C: # _Names_ABs 

670 s, a = self._Inversa12(A, B) 

671 X.set_(latA=A.lat2, lonA=A.lon2, aMM=a, # assert sA == A.s12 

672 latB=B.lat2, lonB=B.lon2, sMM=s) # assert sB == B.s12 

673 return X, A, iA, B, iB 

674 

675 def Middle5(self, glA, glB, **unused): 

676 '''Get the mid-points on two geodesic line segments and their distance. 

677 

678 @return: A L{Middle5Tuple}. 

679 ''' 

680 X, A, iA, B, iB = self._middle5(glA, glB, _C=True) 

681 A, B, s, a, c = self._In5T(A, B, X, X, _2X=_M_) 

682 return Middle5Tuple(self._illz2G(A, iA), 

683 self._illz2G(B, iB), s, a, c) 

684 

685 def Next(self, glA, glB, eps1=None, **_C): # PYCHOK no cover 

686 '''Find the next intersection of two I{intersecting} geodesic lines. 

687 

688 @kwarg _C: Use C{B{_C}=True} to include the option C{"-C"} results (C{bool}). 

689 

690 @return: An L{XDict}. 

691 ''' 

692 if eps1 or _C: 

693 _C = self._xNext(glA, glB, eps1, **_C) 

694 return self._XDictInvoke(self._n_alt, NN, 

695 (glA.lat1, glA.lon1, glA.azi1, glB.azi1), 

696 **_C) # _R=None 

697 

698 def Next5(self, glA, glB, **eps1): # PYCHOK no cover 

699 '''Find the next intersection of two I{intersecting} geodesic lines. 

700 

701 @return: An L{Intersectool5Tuple}. 

702 ''' 

703 X = self.Next(glA, glB, _C=True, **eps1) 

704 return self._In5T(glA, glB, X, X) 

705 

706 def _R_option(self, _R=None): 

707 '''(INTERNAL) Get the C{-R maxdist} option. 

708 ''' 

709 return () if _R is None else (_R__, str(_R)) # -R maxdist 

710 

711 def Segment(self, glA, glB, **_C_unused): 

712 '''Find the intersection between two geodesic line segments. 

713 

714 @kwarg _C: Use C{B{_C}=True} to include the option C{"-C"} results (C{bool}). 

715 

716 @return: An L{XDict}. 

717 ''' 

718 X = self._XDictInvoke(self._i_alt, 'k', 

719 (glA.lat1, glA.lon1, glA.lat2, glA.lon2, 

720 glB.lat1, glB.lon1, glB.lat2, glB.lon2), 

721 _C=_xkwds_get(_C_unused, _C=False)) # _R=None 

722 try: 

723 ks = self.k2kAkB(int(X.k)) 

724 except Exception as x: 

725 raise GeodesicError(glA=glA, glB=glB, X=str(X), cause=x) 

726 return X.set_(**ks) 

727 

728 def Segment5(self, glA, glB, **unused): 

729 '''Find the next intersection of two I{intersecting} geodesic lines. 

730 

731 @return: An L{Intersectool5Tuple}. 

732 ''' 

733 X = self.Segment(glA, glB, _C=True) 

734 return self._In5T(glA, glB, X, X, k2=True) 

735 

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

737 '''Return this C{Intersectool} as string. 

738 

739 @kwarg prec_sep: Keyword argumens C{B{prec}=6} and C{B{sep}=", "} 

740 for the C{float} C{prec}ision, number of decimal digits 

741 (0..9) and the C{sep}arator string to join. Trailing 

742 zero decimals are stripped for B{C{prec}} values of 1 

743 and above, but kept for negative B{C{prec}} values. 

744 

745 @return: Intersectool items (C{str}). 

746 ''' 

747 d = dict(geodesic=self.geodesic, invokation=self.invokation, 

748 status=self.status, 

749 IntersectTool=self.IntersectTool) 

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

751 

752 def _XDictInvoke(self, alt, _k_sX0, args, _C=False, **_R): 

753 '''(INTERNAL) Invoke C{IntersectTool}, return results as C{XDict} or 

754 a C{generator} if keyword argument C{B{_R}=sMaX0} is specified. 

755 ''' 

756 # assert len(args) == {self._c_alt: 6, 

757 # self._i_alt: 8, 

758 # self._n_alt: 4, 

759 # self._o_alt: 8}.get(alt, len(args)) 

760 cmd = self._cmdBasic 

761 Names = self._Names_XDict # has _c_ always 

762 if _k_sX0: 

763 Names += _k_sX0, 

764 if _C: 

765 cmd += self._C_option 

766 Names += self._Names_ABs 

767 if _R: 

768 cmd += self._R_option(**_R) 

769 X, _R = self._DictInvoke2(cmd + alt, args, Names, XDict, **_R) 

770 return X if _R else X.set_(c=int(X.c)) # generator or XDict 

771 

772 

773class Intersector(_IntersectBase): 

774 '''Finder of intersections between two goedesic lines, each an instance 

775 of L{GeodesicLineExact<pygeodesy.geodesicx.GeodesicLineExact>}, 

776 wrapped L{GeodesicLine<pygeodesy.geodesicw.GeodesicLine>} or 

777 L{GeodesicLineSolve<pygeodesy.geodsolve.GeodesicLineSolve>}. 

778 

779 @see: I{Karney}'s C++ class U{Intersect<https://GeographicLib.sourceforge.io/ 

780 C++/doc/classGeographicLib_1_1Intersect.html#details>} for more details. 

781 ''' 

782 

783 def __init__(self, geodesic, **name): 

784 '''New L{Intersector}. 

785 

786 @arg geodesic: The geodesic (L{GeodesicExact<pygeodesy.geodesicx.GeodesicExact>}, 

787 wrapped L{Geodesic<pygeodesy.geodesicw.Geodesic>} or 

788 L{GeodesicSolve<pygeodesy.geodsolve.GeodesicSolve>}). 

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

790 

791 @raise GeodesicError: The eccentricity of the B{C{geodesic}}'s ellipsoid is too 

792 large or no initial convergence. 

793 

794 @see: The B{Note} at I{Karney}'s C++ U{Intersect<https://GeographicLib.sourceforge.io/ 

795 C++/doc/classGeographicLib_1_1Intersect.html#ae41f54c9a44836f6c8f140f6994930cf>}. 

796 ''' 

797 _IntersectBase.__init__(self, geodesic, **name) 

798 E = self.ellipsoid 

799 t1 = E.b * PI # min distance between intersects 

800 t2 = self._polarDist2(_90_0)[0] * _2_0 # furthest, closest intersect 

801 t5 = self._Inversa12( _90_0)[0] * _2_0 # longest, shortest geodesic 

802 if self.f > 0: 

803 t3 = self._obliqDist4()[0] 

804 t4 = t1 

805 else: # PYCHOK no cover 

806 t1, t2, t3 = t2, t1, t5 

807 t4, _, _ = self._polarB3() 

808 

809 self._D1 = d1 = t2 * _0_5 # ~E.L tile spacing for Closest 

810 self._D2 = d2 = t3 / _1_5 # tile spacing for Next 

811 self._D3 = d3 = t4 - self.Delta # tile spacing for All 

812 self._T1 = t1 # min distance between intersects 

813 self._T2 = t2 = t1 * _2_0 

814# self._T5 = t5 # not used 

815 if not (d1 < d3 and d2 < d3 and d2 < t2): 

816 t = Fmt.PARENSPACED(_too_('eccentric'), E.e) 

817 raise GeodesicError(ellipsoid=E.toStr(terse=2), txt=t) 

818 

819 def All(self, glA, glB, X0=None, aMaX0=0, **sMaX0_C): # MCCABE 13 

820 '''Yield all intersection of two geodesic lines up to a limit. 

821 

822 @arg glA: A geodesic line (L{Line<Intersector.Line>}). 

823 @arg glB: An other geodesic line (L{Line<Intersector.Line>}). 

824 @kwarg X0: Optional I{origin} for I{L1-distances} (L{XDict}) or 

825 C{None} for the L{Middle<Intersector.Middle>} of both 

826 lines if both are a 4-C{args} L{Line<Intersector.Line>} 

827 or C{InverseLine}, otherwise C{XDiff_(0, 0)}. 

828 @kwarg aMaX0: Upper limit for the I{angular L1-distance} 

829 (C{degrees}) or C{None} or C{0} for unlimited. 

830 @kwarg sMaX0_C: Optional, upper limit C{B{sMaX0}=2*PI*R} for the 

831 I{L1-distance} to B{C{X0}} (C{meter}) and option 

832 C{B{_C}=False} to include the intersection lat-/ 

833 longitudes C{latA}, C{lonA}, C{latB}, C{lonB} and 

834 distances C{sAB} and C{aSB}. 

835 

836 @return: Yield an L{XDict} for each intersection found. 

837 

838 @raise GeodesicError: Geodesic line B{C{glA}} or B{C{glB}} 

839 invalid, incompatible or ill-configured. 

840 

841 @raise IntersectionError: No convergence. 

842 ''' 

843 self._xLines(glA, glB) 

844 if X0 is None: 

845 try: # determine X0 

846 X0, _, _ = self._middle3(glA, glB, True) 

847 except GeodesicError: # no .Distance 

848 X0 = _X000 

849 sMaX0, _C = self._sMaX0_C2(aMaX0, **sMaX0_C) 

850 

851 D, _D = self.Delta, self._cHalf # C++ _d 

852 xMaX0 = sMaX0 + D 

853 m = int(_ceil(xMaX0 / self._D3)) # m x m tiles 

854 d3 = xMaX0 / m 

855 T2d3D = self._T2d3Delta(d3) 

856 

857 C_ = _List(D) # closest coincident 

858 X_ = _List(D) # intersections found 

859 c0 = 0 

860 S_ = list(X0._nmD3(1 - m, m, d3 * _0_5)) 

861 # assert len(S_) == m * m + (m - 1) % 2 

862 while S_: 

863 Q, i = self._Basic2(glA, glB, S_.pop(0)) 

864 if Q in X_: 

865 continue 

866 if Q.c: # coincident intersection # PYCHOK no cover 

867 _X0fx = X0._fixCoincident 

868 Q = _X0fx(Q) # Q = Q' 

869 if c0 and Q in C_: 

870 continue 

871 C_.addend(Q) 

872 # elimate all existing intersections 

873 # on this line (which didn't set c0) 

874 c0 = Q.c 

875 for j, X in _enumereverse(X_): 

876 if _X0fx(X, c0).L1(Q) <= D: # X' == Q 

877 X_.pop(j) 

878 

879 a, s0 = len(X_), Q.sA 

880 args = self._m12_M12_M21(glA, s0) 

881 _cjD = self._conjDist 

882 for s in (-_D, _D): 

883 s += s0 

884 sa = 0 

885 while True: 

886 i += 1 

887 sa = _cjD(glA, s + sa, *args) - s0 

888 X = Q + (sa, sa * c0) 

889 if X_.addend(X, X0.L1(X), i) > xMaX0: 

890 break 

891 

892 elif c0 and Q in C_: # Q.c == 0 

893 continue 

894 else: 

895 a = len(X_) 

896 

897 X_.addend(Q, X0.L1(Q), i + 1) 

898 for X in X_[a:]: # addended Xs 

899 X._skip(S_, T2d3D) 

900 

901 return X_.sorter(sMaX0, self._C, glA, glB, _C=_C) # generator 

902 

903 def All5(self, glA, glB, X0=_X000, **aMaX0_sMaX0_C): 

904 '''Yield all intersection of two geodesic lines up to a limit. 

905 

906 @return: Yield an L{Intersector5Tuple}C{(A, B, sAB, aAB, c)} 

907 for each intersection found. 

908 

909 @see: Methods L{All} for further details. 

910 ''' 

911 for X in self.All(glA, glB, X0=X0, **aMaX0_sMaX0_C): 

912 yield self._In5T(glA, glB, X, X) 

913 

914 def _Basic2(self, glA, glB, S, i=0): 

915 '''(INTERNAL) Get a basic solution. 

916 ''' 

917 X = _copy(S) 

918 for _ in range(_TRIPS): 

919 S = self._Spherical(glA, glB, X) 

920 X += S 

921 i += 1 

922 if X.c or S.L1() <= self._Tol: # or isnan 

923 return self._Delto(X), i 

924 

925 raise IntersectionError(Fmt.no_convergence(S.L1(), self._Tol)) 

926 

927 def _C(self, X, glA, glB, _C=False, _MM=False): 

928 # add the C{_C} items to C{X}, if requested. 

929 if _C: 

930 A = self._Position(glA, X.sA) 

931 B = self._Position(glB, X.sB) 

932 s, a = self._Inversa12(A, B) 

933 X.set_(latA=A.lat2, lonA=A.lon2, 

934 latB=B.lat2, lonB=B.lon2) 

935 if _MM: # in .Middle5 

936 X.set_(sMM=s, aMM=a) 

937 else: 

938 X.set_(sAB=s, aAB=a) 

939 return X 

940 

941 def Closest(self, glA, glB, X0=_X000, **_C): 

942 '''Find the closest intersection of two geodesic lines. 

943 

944 @arg glA: A geodesic line (L{Line<Intersector.Line>}). 

945 @arg glB: An other geodesic line (L{Line<Intersector.Line>}). 

946 @kwarg X0: Optional I{origin} for I{L1-closeness} (L{XDict}). 

947 @kwarg _C: If C{True}, include the lat-/longitudes C{latA}, 

948 C{lonA}, C{latB}, C{lonB} oon and distances C{sAB} 

949 and C{aSB} between the intersections. 

950 

951 @return: The intersection (L{XDict}) or C{None} if none found. 

952 

953 @raise GeodesicError: Geodesic line B{C{glA}} or B{C{glB}} 

954 invalid, incompatible or ill-configured. 

955 

956 @raise IntersectionError: No convergence. 

957 ''' 

958 self._xLines(glA, glB) 

959 Q, d, S_, i = X0, INF, list(X0._nD1(self._D1)), 0 

960 while S_: 

961 X, i = self._Basic2(glA, glB, S_.pop(0), i) 

962 X = X0._fixCoincident(X) 

963 if X.L1(Q) > self.Delta: # X != Q 

964 d0 = X.L1(X0) 

965 if d0 < self._T1: 

966 Q, d, q = X, d0, i 

967 break 

968 if d0 < d or Q is X0: 

969 Q, d, q = X, d0, i 

970 X._skip(S_, self._T2D1Delta) 

971 

972 return None if Q is X0 else self._C(Q, glA, glB, **_C).set_(sX0=d, iteration=q) 

973 

974 def Closest5(self, glA, glB, X0=_X000): 

975 '''Find the closest intersection of two geodesic lines. 

976 

977 @return: An L{Intersector5Tuple}C{(A, B, sAB, aAB, c)} 

978 or C{None} if none found. 

979 

980 @see: Method L{Closest} for further details. 

981 ''' 

982 X = self.Closest(glA, glB, X0=X0) 

983 return X if X is None else self._In5T(glA, glB, X, X) 

984 

985 def _conjDist(self, gl, s, m12=0, M12=1, M21=1, semi=False): 

986 # Find semi-/conjugate point relative to s0 which is close to s1. 

987 # if semi: 

988 # solve for M23 = 0 using dM23 / ds3 = - (1 - M23 * M32) / m23 

989 # else: 

990 # solve for m23 = 0 using dm23 / ds3 = M32 

991 _S2, _abs, _1 = Fsum(s).fsum2_, fabs, _1_0 

992 for _ in range(_TRIPS): 

993 m13, M13, M31 = self._m12_M12_M21(gl, s) 

994 # see "Algorithms for geodesics", eqs. 31, 32, 33. 

995 m23 = m13 * M12 

996 M32 = M31 * M12 

997 if m12: # PYCHOK no cover 

998 m23 -= m12 * M13 

999 if m13: 

1000 M32 += (_1 - M13 * M31) * m12 / m13 

1001 if semi: 

1002 M23 = M13 * M21 

1003 # when m12 -> eps, (1 - M12 * M21) -> eps^2, I suppose. 

1004 if m12 and m13: 

1005 M23 += (_1 - M12 * M21) * m13 / m12 

1006 d = m23 * M23 / (_1 - M23 * M32) 

1007 else: 

1008 d = -m23 / M32 

1009 s, d = _S2(d) 

1010 if _abs(d) <= self._Tol: 

1011 break 

1012 return s 

1013 

1014 _gl3 = None 

1015 

1016 @Property 

1017 def _conjDist3s(self): 

1018 gl, self._gl3, _D = self._gl3, None, self._cHalf 

1019 return tuple(self._conjDist(gl, s) for s in (-_D, 0, _D)) 

1020 

1021 @_conjDist3s.setter # PYCHOK setter! 

1022 def _conjDist3(self, gl): 

1023 # _XLines(gl, gl) 

1024 self._gl3 = gl 

1025 

1026 def _conjDist3Tt_(self, c, X0=_X000): 

1027 for s in self._conjDist3s: 

1028 T = XDict_(s, s * c, c) 

1029 yield self._Delto(T), T.L1(X0) 

1030 

1031 def _conjDist5(self, azi): 

1032 gl = self._Line(azi1=azi) 

1033 s = self._conjDist(gl, self._cHalf) 

1034 X, _ = self._Basic2(gl, gl, XDict_(s * _0_5, -s * _1_5)) 

1035 return s, (X.L1() - s * _2_0), azi, X.sA, X.sB 

1036 

1037 @Property_RO 

1038 def Delta(self): 

1039 '''Get the equality and tiling margin (C{meter}). 

1040 ''' 

1041 return self._cHalf * _EPSr5 # ~15 Km WGS84 

1042 

1043 def _Delto(self, X): 

1044 # copy Delta into X, overriding X's default 

1045 X._Delta = self.Delta # NOT X.set_(self.Delta) 

1046 return X 

1047 

1048 @Property_RO 

1049 def _EPS3R(self): 

1050 return _EPS3 * self.R 

1051 

1052 @Property_RO 

1053 def _faPI_4(self): 

1054 return (self.f + _2_0) * self.a * PI_4 

1055 

1056 @Property_RO 

1057 def _GeodesicLines(self): 

1058 '''(INTERNAL) Get the C{Geodesic...Line} class(es). 

1059 ''' 

1060 return type(self._Line()), 

1061 

1062 def _In5T(self, glA, glB, S, X, k2=False, **_2X): 

1063 # Return an intersection as C{Intersector5Tuple}. 

1064 A = self._Position(glA, S.sA) 

1065 B = self._Position(glB, S.sB) 

1066 if k2: 

1067 A.set_(k2=X.kA) 

1068 B.set_(k2=X.kB) 

1069 s, a = self._Inversa12(A, B) 

1070 return Intersector5Tuple(A._2X(glA, **_2X), 

1071 B._2X(glB, **_2X), s, a, X.c, iteration=X.iteration) 

1072 

1073 def _Inverse(self, A, B): # caps=Caps.STANDARD 

1074 return self._g.Inverse(A.lat2, A.lon2, B.lat2, B.lon2) 

1075 

1076 def Line(self, lat1, lon1, azi1_lat2, *lon2, **name): 

1077 '''Return a geodesic line from this C{Intersector}'s geodesic, specified by 

1078 two (goedetic) points or a (goedetic) point and an (initial) azimuth. 

1079 

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

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

1082 @arg azi1_lat2: Azimuth at the first point (compass C{degrees}) if no 

1083 B{C{lon2}} argument is given, otherwise the latitude of 

1084 the second point (C{degrees}). 

1085 @arg lon2: If given, the longitude of the second point (C{degrees}). 

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

1087 

1088 @return: A line (from L{geodesic<Intersector.geodesic>}C{.Line} or 

1089 C{.InverseLine} method) with C{LINE_CAPS}. 

1090 ''' 

1091 args = self._ll3z4ll(lat1, lon1, azi1_lat2, *lon2) 

1092 gl = self._g.InverseLine(*args, caps=Caps.LINE_CAPS) if lon2 else \ 

1093 self._g.Line( *args, caps=Caps.LINE_CAPS) 

1094 if name: 

1095 gl.name= name 

1096 return gl 

1097 

1098 def _Line(self, lat1=0, lon1=0, azi1=0): 

1099 return self._g.Line(lat1, lon1, azi1, caps=Caps.LINE_CAPS) 

1100 

1101 def Middle(self, glA, glB, raiser=True, **_C): 

1102 '''Get the mid-points on two geodesic line segments. 

1103 

1104 @arg glA: A geodesic line (L{Line<Intersector.Line>}, 4-C{args}). 

1105 @arg glB: An other geodesic line (L{Line<Intersector.Line>}, 4-C{args}). 

1106 @kwarg raiser: If C{True}, check that B{C{glA}} and B{C{glB}} are a 

1107 4-C{args} L{Line<Intersector.Line>} or C{InverseLine} 

1108 (C{bool}). 

1109 @kwarg _C: If C{True}, include the lat-/longitudes C{latA}, C{lonA}, 

1110 C{latB}, C{lonB} of the mid-points and half-lengths C{sA} 

1111 and C{sB} in C{meter} of the respective line segments. 

1112 

1113 @return: The mid-point and half-length of each segment (L{XDict}), 

1114 B{C{_C}} above. 

1115 

1116 @raise GeodesicError: Geodesic line B{C{glA}} or B{C{glB}} invalid, 

1117 incompatible, ill-configured or not a 4-C{args 

1118 Line} or other C{InverseLine}. 

1119 ''' 

1120 M, _, _ = self._middle3(glA, glB, raiser) 

1121 return self._C(M, glA, glB, **_C) if _C else M 

1122 

1123 def _middle3(self, glA, glB, raiser): # in .All, .Segment 

1124 # return segment length C{sA} and C{sB} and the 

1125 # center C{X0} of rectangle [sA, sB] 

1126 self._xLines(glA, glB, s13=raiser) # need .Arc, .Distance 

1127 sA = glA.Distance() 

1128 sB = glB.Distance() 

1129 X = XDict_(sA * _0_5, sB * _0_5) 

1130 # _ = X._outSide(sA, sB) 

1131 return self._Delto(X), sA, sB 

1132 

1133 def Middle5(self, glA, glB, raiser=True): 

1134 '''Get the mid-points of two geodesic line segments and distances. 

1135 

1136 @return: A L{Middle5Tuple}C{(A, B, sMM, aMM, c)}. 

1137 

1138 @see: Method L{Middle} for further details. 

1139 ''' 

1140 M, _, _ = self._middle3(glA, glB, raiser) 

1141 M = self._C(M, glA, glB, _C=True, _MM=True) 

1142 A, B, s, a, c = self._In5T(glA, glB, M, M, _2X=_M_) 

1143 return Middle5Tuple(self._illz2G(A, glA), 

1144 self._illz2G(B, glB), s, a, c) 

1145 

1146 def _m12_M12_M21(self, gl, s): 

1147 P = gl.Position(s, outmask=Caps._REDUCEDLENGTH_GEODESICSCALE) 

1148 return P.m12, P.M12, P.M21 

1149 

1150 def Next(self, glA, glB, eps1=None, **_C): # PYCHOK no cover 

1151 '''Yield the next intersection of two I{intersecting} geodesic lines. 

1152 

1153 @arg glA: A geodesic line (L{Line<Intersector.Line>}). 

1154 @arg glB: An other geodesic line (L{Line<Intersector.Line>}). 

1155 @kwarg eps1: Optional margin for the L{euclid<pygeodesy.euclid>}ean 

1156 distance (C{degrees}) between the C{(lat1, lon1)} points 

1157 of both lines or C{None} for unchecked. 

1158 @kwarg _C: If C{True}, include the lat-/longitudes C{latA}, C{lonA}, 

1159 C{latB}, C{lonB} of and distances C{sAB} and C{aSB} 

1160 between the intersections. 

1161 

1162 @return: The intersection (L{XDict}) or C{None} if none found. 

1163 

1164 @raise GeodesicError: Geodesic line B{C{glA}} or B{C{glB}} invalid, 

1165 incompatible, ill-configured or C{(lat1, lon1)} 

1166 not B{C{eps1}}-equal. 

1167 

1168 @raise IntersectionError: No convergence. 

1169 

1170 @note: Offset C{X0} is implicit, zeros. 

1171 ''' 

1172 self._xLines(glA, glB) 

1173 if eps1 or _C: # eps 

1174 _C = self._xNext(glA, glB, eps1, **_C) 

1175 

1176 X0, self._conjDist3s = _X000, glA # reset Property 

1177 Q, d, S_, i = _XINF, INF, list(X0._nD2(self._D2)), 0 

1178 while S_: 

1179 X, i = self._Basic2(glA, glB, S_.pop(0), i) 

1180 X = X0._fixCoincident(X) 

1181 t = X.L1(X0) # == X.L1() 

1182 c, z = X.c, (t <= self.Delta) # X == X0 

1183 if z: 

1184 if not c: 

1185 continue 

1186 Tt_ = self._conjDist3Tt_(c, X0) 

1187 else: 

1188 Tt_ = (X, t), 

1189 

1190 for T, t in Tt_: 

1191 if t < d or Q is _XINF: 

1192 Q, d, q = T, t, i 

1193 i += 1 

1194 

1195 for s in ((_1_1t if z else _1_0_1t) 

1196 if c else _0t): 

1197 T = X 

1198 if s and c: 

1199 s *= self._D2 

1200 T = X + (s, s * c) # NOT += 

1201 T._skip(S_, self._T2D2Delta) 

1202 

1203 return None if Q is _XINF else self._C(Q, glA, glB, **_C).set_(sX0=d, iteration=q) 

1204 

1205 def Next5(self, glA, glB, **eps1): # PYCHOK no cover 

1206 '''Yield the next intersection of two I{intersecting} geodesic lines. 

1207 

1208 @return: An L{Intersector5Tuple}C{(A, B, sAB, aAB, c)} or C{None} 

1209 if none found. 

1210 

1211 @see: Method L{Next} for further details. 

1212 ''' 

1213 X = self.Next(glA, glB, **eps1) 

1214 return X if X is None else self._In5T(glA, glB, X, X) 

1215 

1216 def _obliqDist4(self): 

1217 zx = _45_0 

1218 if self.f: 

1219 _abs, _cjD5 = fabs, self._conjDist5 

1220 

1221 _, ds0, z0, _, _ = _cjD5(zx + _1_0) 

1222 s1, ds1, z1, sAx, sBx = _cjD5(zx - _1_0) 

1223 sx, dsx, zx = s1, _abs(ds1), z1 

1224 # find ds(azi) = 0 by secant method 

1225 for _ in range(16): 

1226 if ds1 == ds0: 

1227 break 

1228 z = (z0 * ds1 - z1 * ds0) / (ds1 - ds0) 

1229 _, ds0, z0 = s1, ds1, z1 

1230 s1, ds1, z1, a, b = _cjD5(z) 

1231 if _abs(ds1) < dsx: 

1232 sx, dsx, zx, sAx, sBx = s1, _abs(ds1), z, a, b 

1233 if not dsx: 

1234 break 

1235 else: 

1236 sx, sAx, sBx = self._cHalf, _0_5, -_1_5 

1237 return sx, zx, sAx, sBx 

1238 

1239 def _polarB3(self, lats=False): # PYCHOK no cover 

1240 latx = _64_0 

1241 lat = _90_0 - latx 

1242 if self.f: 

1243 _d, _pD2 = fdot, self._polarDist2 

1244 

1245 s0, lat0 = _pD2(latx - _1_0) 

1246 s1, lat1 = _pD2(latx + _1_0) 

1247 s2, lat2 = \ 

1248 sx, latx = _pD2(latx) 

1249 prolate = self.f < 0 

1250 # solve for ds(lat) / dlat = 0 with a quadratic fit 

1251 for _ in range(_TRIPS): 

1252 t = (lat1 - lat0), (lat0 - lat2), (lat2 - lat1) 

1253 d = _d(t, s2, s1, s0) * _2_0 

1254 if not d: # or isnan(d) 

1255 break 

1256 lat = _d(t, (lat1 + lat0) * s2, 

1257 (lat0 + lat2) * s1, 

1258 (lat2 + lat1) * s0) / d 

1259 s0, lat0 = s1, lat1 

1260 s1, lat1 = s2, lat2 

1261 s2, lat2 = _pD2(lat) 

1262 if (s2 < sx) if prolate else (s2 > sx): 

1263 sx, latx = s2, lat2 

1264 if lats: 

1265 _, lat = _pD2(latx, lat2=True) 

1266 sx += sx 

1267 else: 

1268 sx = self._cHalf 

1269 return sx, latx, lat 

1270 

1271 def _polarDist2(self, lat1, lat2=False): 

1272 gl = self._Line(lat1=lat1) 

1273 s = self._conjDist(gl, self._faPI_4, semi=True) 

1274 if lat2: 

1275 lat1 = gl.Position(s, outmask=Caps.LATITUDE).lat2 

1276 return s, lat1 

1277 

1278 def _Position(self, gl, s): 

1279 return gl.Position(s, outmask=Caps._STD_LINE) 

1280 

1281 def Segment(self, glA, glB, proven=None, raiser=True, **_C): 

1282 '''Find the intersection between two geodesic line segments. 

1283 

1284 @kwarg proven: Conjecture is that whenever two geodesic line 

1285 segments intersect, the intersection is the 

1286 one closest to the mid-points of segments. 

1287 If so, use C{B{proven}=True}, otherwise find 

1288 intersections on the segments and specify 

1289 C{B{proven}=None} to return the first or 

1290 C{B{proven}=False} the closest (C{bool}). 

1291 @kwarg raiser: If C{True}, check that B{C{glA}} and B{C{glB}} 

1292 are a 4-C{args} L{Line<Intersector.Line>} or 

1293 C{InverseLine} (C{bool}). 

1294 @kwarg _C: If C{True}, include the lat-/longitudes C{latA}, 

1295 C{lonA}, C{latB}, C{lonB} of and distances C{sAB} 

1296 and C{aSB} between the intersections. 

1297 

1298 @return: The intersection of the segments (L{XDict}) with 

1299 indicators C{kA}, C{kB} and C{k} set or if no 

1300 intersection is found, C{None}. 

1301 

1302 @raise GeodesicError: Geodesic line B{C{glA}} or B{C{glB}} 

1303 invalid, incompatible, ill-configured or 

1304 not an C{InverseLine} or 4-C{args Line}. 

1305 

1306 @raise IntersectionError: No convergence. 

1307 

1308 @see: Method L{Middle<Intersector.Middle>} for further details. 

1309 ''' 

1310 X0, sA, sB = self._middle3(glA, glB, raiser) 

1311 Q = self.Closest(glA, glB, X0) # to X0 

1312 if Q is not None: 

1313 if Q.c: # anti-/parallel 

1314 Q._fixSegment(sA, sB) 

1315 # are rectangle [sA, sB] corners further from X0 than Q? 

1316 d0 = X0.L1(Q) 

1317 if Q._outSide(sA, sB) and d0 <= X0.L1() and not proven: 

1318 i = Q.iteration 

1319 for T in Q._corners(sA, sB, self._T2): 

1320 X, i = self._Basic2(glA, glB, T, i) 

1321 X = T._fixCoincident(X) 

1322 if not X._outSide(sA, sB): 

1323 d = X0.L1(X) 

1324 if d < d0 or proven is None: 

1325 Q, d0 = X, d 

1326 if proven is None: 

1327 break 

1328 Q.set_(iteration=i) 

1329 

1330 Q = self._C(Q, glA, glB, **_C).set_(sX0=d0) 

1331 return Q 

1332 

1333 def Segment5(self, glA, glB, **proven_raiser): 

1334 '''Find the intersection between two geodesic line segments. 

1335 

1336 @return: An L{Intersector5Tuple}C{(A, B, sAB, aAB, c)} 

1337 or C{None} if none found. 

1338 

1339 @see: Method L{Segment} for further details. 

1340 ''' 

1341 X = self.Segment(glA, glB, **proven_raiser) 

1342 return X if X is None else self._In5T(glA, glB, X, X, k2=True) 

1343 

1344 def _Spherical(self, glA, glB, S): 

1345 '''(INTERNAL) Get solution based from a spherical triangle. 

1346 ''' 

1347 # threshold for coincident geodesics/intersections ~4.3 nm WGS84. 

1348 A = self._Position(glA, S.sA) 

1349 B = self._Position(glB, S.sB) 

1350 D = self._Inverse(A, B) 

1351 

1352 a, da = _diff182(A.azi2, D.azi1) # interior angle at A 

1353 b, db = _diff182(B.azi2, D.azi2) # exterior angle at B 

1354 c, dc = _diff182(a, b) 

1355 if fsum1_(dc, db, -da, c) < 0: # inverted triangle 

1356 a, da = -a, -da 

1357 b, db = -b, -db 

1358 sa, ca = _sincos2de(a, da) 

1359 sb, cb = _sincos2de(b, db) 

1360 

1361 e, z, _abs = _EPS3, D.s12, fabs 

1362 if _abs(z) <= self._EPS3R: # XXX z <= ... 

1363 sA = sB = 0 # at intersection 

1364 c = 1 if _abs(sa - sb) <= e and _abs(ca - cb) <= e else ( 

1365 -1 if _abs(sa + sb) <= e and _abs(ca + cb) <= e else 0) 

1366 elif _abs(sa) <= e and _abs(sb) <= e: # coincident 

1367 sA = ca * z * _0_5 # choose mid-point 

1368 sB = -cb * z * _0_5 

1369 c = 1 if (ca * cb) > 0 else -1 

1370 # alt1: sA = ca * z; sB = 0 

1371 # alt2: sB = -cb * z; sA = 0 

1372 else: # general case 

1373 sz, cz = sincos2(z / self.R) 

1374 # [SKIP: Divide args by |sz| to avoid possible underflow 

1375 # in {sa, sb} * sz; this is probably not necessary]. 

1376 # Definitely need to treat sz < 0 (z > PI*R) correctly in 

1377 # order to avoid some convergence failures in _Basic2. 

1378 sA = atan2(sb * sz, sb * ca * cz - sa * cb) * self.R 

1379 sB = atan2(sa * sz, -sa * cb * cz + sb * ca) * self.R 

1380 c = 0 

1381 return XDict_(sA, sB, c) # no ._Delto 

1382 

1383 @Property_RO 

1384 def _T2D1Delta(self): 

1385 return self._T2d3Delta(self._D1) 

1386 

1387 @Property_RO 

1388 def _T2D2Delta(self): 

1389 return self._T2d3Delta(self._D2) 

1390 

1391 def _T2d3Delta(self, d3): 

1392 return self._T2 - d3 - self.Delta 

1393 

1394 @Property_RO 

1395 def _Tol(self): # convergence tolerance 

1396 return self._cHalf * _EPSjam 

1397 

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

1399 '''Return this C{Intersector} as string. 

1400 

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

1402 for further details. 

1403 

1404 @return: C{Intersector} (C{str}). 

1405 ''' 

1406 return self._instr(props=(Intersector.geodesic,), **prec_sep_name) 

1407 

1408 def _xLines(self, glA, glB, s13=False): 

1409 # check two geodesic lines vs this geodesic 

1410 C, gls = Caps.LINE_CAPS, dict(glA=glA, glB=glB) 

1411 _xinstanceof(*self._GeodesicLines, **gls) 

1412 for n, gl in gls.items(): 

1413 try: 

1414 _xgeodesics(gl.geodesic, self.geodesic) 

1415 if s13 and not isfinite(gl.s13): # or not gl.caps & Caps.DISTANCE_IN 

1416 t = gl.geodesic.InverseLine.__name__ 

1417 raise TypeError(_not_(_an(t))) 

1418 c = gl.caps & C 

1419 if c != C: # not gl.caps_(C) 

1420 c, C, x = map1(bin, c, C, _xor(c, C)) 

1421 x = _SPACE_(_xor.__name__, repr(x))[1:] 

1422 raise GeodesicError(caps=c, LINE_CAPS=C, txt=x) 

1423 except Exception as x: 

1424 raise GeodesicError(n, gl, cause=x) 

1425 

1426 

1427class Intersect7Tuple(_NamedTuple): 

1428 '''7-Tuple C{(A, B, sAB, aAB, c, kA, kB)} with C{A} and C{B} each 

1429 a C{LatLon} or L{LatLon4Tuple}C{(lat, lon, height, datum)} of 

1430 the intersection on each geodesic line, the distance C{sAB} in 

1431 in C{meter} and angular distance C{aAB} in C{degrees} between 

1432 C{A} and C{B}, coincidence indicator C{c} and segment indicators 

1433 C{kA} and C{kB} all C{int}, see L{XDict} and method U{intersect7 

1434 <_IntersectBase.intersect7>}. 

1435 ''' 

1436 _Names_ = (_A_, _B_, _sAB_, _aAB_, _c_, 'kA', 'kB') 

1437 _Units_ = (_Pass, _Pass, Meter, Degrees, Int, Int, Int) 

1438 

1439 

1440class Intersectool5Tuple(_NamedTuple): 

1441 '''5-Tuple C{(A, B, sAB, aAB, c)} with C{A} and C{B} the C{Position} 

1442 of the intersection on each geodesic line, the distance C{sAB} 

1443 between C{A} and C{B} in C{meter}, the angular distance C{aAB} in 

1444 C{degrees} and coincidence indicator C{c} (C{int}), see L{XDict}. 

1445 

1446 @note: C{A} and C{B} are each a C{GDict} with C{lat1}, C{lon1} and 

1447 C{azi1} or C{lat2}, C{lon2} from the geodesic line C{glA} 

1448 respectively C{glB} and the intersection location in C{latX}, 

1449 C{lonX}, distance C{s1X} in C{meter} and angular distance 

1450 C{a1M} in C{degrees} and the segment indicator C{kX}. See 

1451 L{XDict} for more details. 

1452 ''' 

1453 _Names_ = Intersect7Tuple._Names_[:5] 

1454 _Units_ = Intersect7Tuple._Units_[:5] 

1455 

1456 

1457class Intersector5Tuple(Intersectool5Tuple): 

1458 '''5-Tuple C{(A, B, sAB, aAB, c)} with C{A} and C{B} the C{Position} 

1459 of the intersection on each geodesic line, the distance C{sAB} 

1460 between C{A} and C{B} in C{meter}, angular distance C{aAB} in 

1461 C{degrees} and coincidence indicator C{c} (C{int}), see L{XDict}. 

1462 

1463 @note: C{A} and C{B} are each a C{GeodesicLine...Position} for 

1464 C{outmask=Caps.STANDARD} with the intersection location in 

1465 C{latX}, C{lonX}, azimuth in C{aziX}, distance C{s1X} in 

1466 C{meter} and angular distance C{a1X} in C{degrees} and the 

1467 segment indicator C{kX}. See L{XDict} for more details. 

1468 ''' 

1469 _Names_ = Intersectool5Tuple._Names_ 

1470 

1471 

1472class Middle5Tuple(Intersectool5Tuple): 

1473 '''5-Tuple C{(A, B, sMM, aMM, c)} with C{A} and C{B} the I{line segments} 

1474 including the mid-point location in C{latM}, C{lonM}, distance C{s1M} 

1475 in C{meter} and angular distance C{a1M} in C{degrees}, the distance 

1476 between both mid-points C{sMM} in C{meter} and angular distance C{aMM} 

1477 in C{degrees} and coincidence indicator C{c} (C{int}). See L{XDict} 

1478 for more details. 

1479 ''' 

1480 _Names_ = (_A_, _B_, 'sMM', 'aMM', _c_) 

1481 

1482 

1483class _List(list): 

1484 

1485 _Delta = 0 # equality margin 

1486 

1487 def __init__(self, Delta): 

1488 self._Delta = Delta 

1489# list.__init__(self) 

1490 

1491 def __contains__(self, other): 

1492 # handle C{if X in this: ...} 

1493 a, b = other.sA, other.sB 

1494 D, _D1 = self._Delta, _L1 

1495 for X in self: 

1496 if _D1(X.sA - a, X.sB - b) <= D: 

1497 return True 

1498 return False 

1499 

1500 def addend(self, X, *d0_i): 

1501 # append an item, updated 

1502 if d0_i: 

1503 d0, i = d0_i 

1504 X.set_(sX0=d0, iteration=i) 

1505 self.append(X) 

1506 return X.sX0 

1507 

1508 def sorter(self, sMaX0, dot_C, glA, glB, **_C): 

1509 # trim and sort the X items 

1510 

1511 def _key(X): 

1512 return X.sX0 # rank of X 

1513 

1514 t = (X for X in self if X.sX0 <= sMaX0) 

1515 for X in sorted(t, key=_key): 

1516 yield dot_C(X, glA, glB, **_C) if _C else X 

1517 

1518 

1519def _L1(a, b): 

1520 '''(INTERNAL) Return the I{L1} distance. 

1521 ''' 

1522 return fabs(a) + fabs(b) 

1523 

1524 

1525__all__ += _ALL_DOCS(_IntersectBase) 

1526 

1527if __name__ == '__main__': # MCCABE 14 

1528 

1529 from pygeodesy import printf 

1530 __help_ = '--help' 

1531 

1532 def _main(args): 

1533 

1534 from pygeodesy import GeodesicExact 

1535 from pygeodesy.internals import _plural, _usage 

1536 from pygeodesy.interns import _COLONSPACE_, _DOT_, _EQUAL_, \ 

1537 _i_, _m_, _n_, _version_, _X_ 

1538 import re 

1539 

1540 class XY0(Float): 

1541 pass 

1542 

1543 def _opts(_h): # for _usage() 

1544 ll4 = ' latA1 lonA1' 

1545 ll4 += ll4.replace('1', '2') 

1546 ll4 += ll4.replace(_A_, _B_) 

1547 llz = _SPACE_(NN, _latA_, _lonA_, 'aziA') 

1548 llz2 = llz + llz.replace(_A_, _B_) 

1549 return dict(opts='-Verbose|V--version|v--help|h--Tool|T--Check|C-R <meter>-', 

1550 alts=((_c_ + llz2), 

1551 (_i_ + ll4), 

1552 (_m_ + ll4), 

1553 (_n_ + llz + ' aziB'), 

1554 ('o' + llz2 + ' x0 y0')), 

1555 help=_h if isinstance(_h, str) else NN) 

1556 

1557 def _starts(Opt, arg): 

1558 return arg == Opt[1:3] or (len(arg) > 2 and Opt.startswith(arg)) 

1559 

1560 _isopt = re.compile('^[-]+[a-z]*$', flags=re.IGNORECASE).match 

1561 

1562 I = Intersector(GeodesicExact()) # PYCHOK I 

1563 M = m = _R = None 

1564 _T = _V = _h = _C = False 

1565 

1566 while args and _isopt(args[0]): 

1567 arg = args.pop(0) 

1568 if arg == _c__: 

1569 M, m = I.Closest, 6 # latA lonA aziA latB lonB aziB 

1570 elif _starts('--Check', arg): 

1571 _C = True 

1572 elif _starts(__help_, arg): 

1573 _h = args[0] if args and _isopt(args[0]) else True 

1574 elif arg == _i__: 

1575 M, m = I.Segment, 8 # latA1 lonA1 latA2 lonA2 latB1 lonB1 latB2 lonB2 

1576 elif arg == '-m': 

1577 M, m = I.Middle, 8 # latA1 lonA1 latA2 lonA2 latB1 lonB1 latB2 lonB2 

1578 _R = None # zap -R 

1579 elif arg == _n__: 

1580 M, m = I.Next, 4 # latA lonA aziA aziB 

1581 elif arg == _o__: 

1582 M, m = I.Closest, 8 # latA lonA aziA latB lonB aziB x0 y0 

1583 elif arg == _R__ and args: 

1584 _R = args.pop(0) 

1585 elif _starts('--Tool', arg): 

1586 I = Intersectool() # PYCHOK I 

1587 if _V: 

1588 I.verbose = True 

1589 if not _Xables.X_OK(I.IntersectTool): 

1590 I.IntersectTool = _Xables.IntersectTool(_Xables.bin_) 

1591 elif _V: 

1592 _ = I.version 

1593 M, _T = None, True 

1594 elif _starts('--Verbose', arg): 

1595 _V = True 

1596 if _T: 

1597 I.verbose = True 

1598 elif _starts('--version', arg): 

1599 printf(_COLONSPACE_(*((_version_, I.version) if _T else 

1600 (__version__, repr(I))))) 

1601 else: 

1602 raise ValueError('invalid option %r' % (arg,)) 

1603 

1604 if _h or M is None: 

1605 printf(_usage(__file__, **_opts(_h)), nl=1) 

1606 else: 

1607 n = len(args) 

1608 if n < m: 

1609 n = _plural('only %s arg' % (n,), n) if n else 'no args' 

1610 raise ValueError('%s, need %s' % (n, m)) 

1611 args[:] = args[:m] 

1612 

1613 kwds = dict(_C=True) if _C else {} 

1614 if M == I.Next: # -n 

1615 # get latA lonA aziA latA lonA aziB 

1616 args[3:] = args[:2] + args[3:4] 

1617 elif M == I.Closest and m > 6: # -o 

1618 y0 = Meter(y0=args.pop()) 

1619 x0 = Meter(x0=args.pop()) 

1620 kwds.update(X0=XDict_(x0, y0)) 

1621 if _R: 

1622 m = Meter_(_R, name=_R__, low=0) 

1623 kwds.update(sMaX0=m) 

1624 M = I.All 

1625 

1626 n = len(args) // 2 

1627 glA = I.Line(*args[:n]) 

1628 glB = I.Line(*args[n:]) 

1629 

1630 m = _DOT_(I.__class__.__name__, M.__name__) 

1631 if _V: 

1632 X = _SPACE_(_X_, _EQUAL_, m) 

1633 printf(unstr(X, glA, glB, **kwds)) 

1634 

1635 X = M(glA, glB, **kwds) 

1636 if X is None or isinstance(X, (XDict, tuple)): 

1637 printf(_COLONSPACE_(m, repr(X))) 

1638 else: 

1639 for i, X in enumerate(X): 

1640 printf(_COLONSPACE_(Fmt.INDEX(m, i), repr(X))) 

1641 

1642 def _examples(): 

1643 

1644 from pygeodesy.internals import _usage_argv 

1645 

1646 s = _SPACE_(*_usage_argv(__file__)) 

1647 for t in ('-h', '-h -n', 

1648 '-c 0 0 45 40 10 135', 

1649 '-C -c 0 0 45 40 10 135', 

1650 '-T -R 2.6e7 -c 0 0 45 40 10 135', 

1651 '-c 50 -4 -147.7 0 0 90', 

1652 '-C -c 50 -4 -147.7 0 0 90', 

1653 '# % echo 0 0 10 10 50 -4 50S 4W | IntersectTool -i -p 0 -C', 

1654 '# -631414 5988887 0 -3', 

1655 '# -4.05187 -4.00000 -4.05187 -4.00000 0', 

1656 '-m 0 0 10 10 50 -4 50S 4W', 

1657 '-C -m 0 0 10 10 50 -4 50S 4W', 

1658 '-i 0 0 10 10 50 -4 50S 4W', 

1659 '-T -i 0 0 10 10 50 -4 50S 4W', 

1660 '-C -i 0 0 10 10 50 -4 50S 4W', 

1661 '-T -C -i 0 0 10 10 50 -4 50S 4W', 

1662 '-V -T -i 0 0 10 10 50 -4 -50 -4', 

1663 '-C -R 4e7 -c 50 -4 -147.7 0 0 90', 

1664 '-T -C -R 4e7 -c 50 -4 -147.7 0 0 90', 

1665 '-R 4e7 -i 0 0 10 10 50 -4 -50 -4', 

1666 '-T -R 4e7 -i 0 0 10 10 50 -4 -50 -4'): 

1667 if t.startswith(_HASH_): 

1668 printf(t, nl=int(t[2] == '%')) 

1669 else: 

1670 printf(_SPACE_(_HASH_, s, t), nl=1) 

1671 argv[1:] = t = t.split() 

1672 _main(t) 

1673 

1674 from sys import argv, stderr 

1675 try: 

1676 if len(argv) == 2 and argv[1] == __help_: 

1677 _examples() 

1678 else: 

1679 _main(argv[1:]) 

1680 

1681 except Exception as x: 

1682 x = _SPACE_(x, NN, _HASH_, *argv) 

1683 printf(x, file=stderr, nl=1) 

1684 if '-V' in x or _MODS.errors.exception_chaining(): 

1685 raise 

1686 exit(1) 

1687 

1688# % env PYGEODESY_INTERSECTTOOL=... python3 -m pygeodesy.geodesici --help 

1689 

1690# % python3 -m pygeodesy.geodesici -h 

1691# 

1692# usage: python3 -m ....pygeodesy.geodesici [--Verbose | -V] [--version | -v] [--help | -h] [--Tool | -T] [--Check | -C] [-R meter] 

1693# [-c latA lonA aziA latB lonB aziB | 

1694# -i latA1 lonA1 latA2 lonA2 latB1 lonB1 latB2 lonB2 | 

1695# -m latA1 lonA1 latA2 lonA2 latB1 lonB1 latB2 lonB2 | 

1696# -n latA lonA aziA aziB | 

1697# -o latA lonA aziA latB lonB aziB x0 y0] 

1698 

1699# % python3 -m ....pygeodesy.geodesici -h -n 

1700# 

1701# usage: python3 -m ....pygeodesy.geodesici -n latA lonA aziA aziB 

1702 

1703# % python3 -m ....pygeodesy.geodesici -c 0 0 45 40 10 135 

1704# Intersector.Closest: XDict(c=0, sA=3862290.547855, sB=2339969.547699, sX0=6202260.095554) 

1705 

1706# % python3 -m ....pygeodesy.geodesici -C -c 0 0 45 40 10 135 

1707# Intersector.Closest: XDict(aAB=0.0, c=0, latA=23.875306, latB=23.875306, lonA=26.094096, lonB=26.094096, sA=3862290.547855, sAB=0.0, sB=2339969.547699, sX0=6202260.095554) 

1708 

1709# % env PYGEODESY_INTERSECTTOOL=...python3 -m ....pygeodesy.geodesici -T -R 2.6e7 -c 0 0 45 40 10 135 

1710# Intersectool.All[0]: XDict(c=0, sA=3862290.547855, sB=2339969.547699, sX0=6202260.095554) 

1711 

1712# % python3 -m ....pygeodesy.geodesici -c 50 -4 -147.7 0 0 90 

1713# Intersector.Closest: XDict(c=0, sA=6058048.653081, sB=-3311252.995823, sX0=9369301.648903) 

1714 

1715# % python3 -m ....pygeodesy.geodesici -C -c 50 -4 -147.7 0 0 90 

1716# Intersector.Closest: XDict(aAB=0.0, c=0, latA=0.0, latB=-0.0, lonA=-29.745492, lonB=-29.745492, sA=6058048.653081, sAB=0.0, sB=-3311252.995823, sX0=9369301.648903) 

1717 

1718# % echo 0 0 10 10 50 -4 50S 4W | IntersectTool -i -p 0 -C 

1719# -631414 5988887 0 -3 

1720# -4.05187 -4.00000 -4.05187 -4.00000 0 

1721 

1722# % python3 -m ....pygeodesy.geodesici -m 0 0 10 10 50 -4 50S 4W 

1723# Intersector.Middle: XDict(c=0, sA=782554.549609, sB=5536835.161499, sX0=0.0) 

1724 

1725# % python3 -m ....pygeodesy.geodesici -C -m 0 0 10 10 50 -4 50S 4W 

1726# Intersector.Middle: XDict(aAB=10.262308, c=0, latA=5.019509, latB=0.036282, lonA=4.961883, lonB=-4.0, sA=782554.549609, sAB=1138574.546746, sB=5536835.161499, sX0=0.0) 

1727 

1728# % python3 -m ....pygeodesy.geodesici -i 0 0 10 10 50 -4 50S 4W 

1729# Intersector.Segment: XDict(c=0, k=-3, kA=-1, kB=0, sA=-631414.26877, sB=5988887.278435, sX0=1866020.935315) 

1730 

1731# % env PYGEODESY_INTERSECTTOOL=... python3 -m ....pygeodesy.geodesici -T -i 0 0 10 10 50 -4 50S 4W 

1732# Intersectool.Segment: XDict(c=0, k=-3, kA=-1, kB=0, sA=-631414.26877, sB=5988887.278435) 

1733 

1734# % python3 -m ....pygeodesy.geodesici -C -i 0 0 10 10 50 -4 50S 4W 

1735# Intersector.Segment: XDict(aAB=0.0, c=0, k=-3, kA=-1, kB=0, latA=-4.051871, latB=-4.051871, lonA=-4.0, lonB=-4.0, sA=-631414.26877, sAB=0.0, sB=5988887.278435, sX0=1866020.935315) 

1736 

1737# % env PYGEODESY_INTERSECTTOOL=... python3 -m ....pygeodesy.geodesici -T -C -i 0 0 10 10 50 -4 50S 4W 

1738# Intersectool.Segment: XDict(c=0, k=-3, kA=-1, kB=0, latA=-4.051871, latB=-4.051871, lonA=-4.0, lonB=-4.0, sA=-631414.26877, sAB=0.0, sB=5988887.278435) 

1739 

1740# % env PYGEODESY_INTERSECTTOOL=... python3 -m ....pygeodesy.geodesici -V -T -i 0 0 10 10 50 -4 -50 -4 

1741# Intersectool@1: /opt/local/bin/IntersectTool --version (invoke) 

1742# Intersectool@1: '/opt/local/bin/IntersectTool: GeographicLib version 2.3' (0) 

1743# Intersectool@1: /opt/local/bin/IntersectTool: GeographicLib version 2.3 (0) 

1744# X = Intersectool.Segment(GDict(lat1=0.0, lat2=10.0, lon1=0.0, lon2=10.0), GDict(lat1=50.0, lat2=-50.0, lon1=-4.0, lon2=-4.0)) 

1745# Intersectool@2: /opt/local/bin/IntersectTool -E -p 10 -i \ 0.0 0.0 10.0 10.0 50.0 -4.0 -50.0 -4.0 (Segment) 

1746# Intersectool@2: '-631414.2687702414 5988887.2784352796 0 -3' (0) 

1747# Intersectool@2: sA=-631414.2687702414, sB=5988887.2784352796, c=0, k=-3 (0) 

1748# Intersectool.Segment: XDict(c=0, k=-3, kA=-1, kB=0, sA=-631414.26877, sB=5988887.278435) 

1749 

1750# % python3 -m ....pygeodesy.geodesici -C -R 4e7 -c 50 -4 -147.7 0 0 90 

1751# Intersector.All[0]: XDict(aAB=0.0, c=0, latA=0.0, latB=-0.0, lonA=-29.745492, lonB=-29.745492, sA=6058048.653081, sAB=0.0, sB=-3311252.995823, sX0=9369301.648903) 

1752# Intersector.All[1]: XDict(aAB=0.0, c=0, latA=0.0, latB=0.0, lonA=150.046964, lonB=150.046964, sA=-13941907.021445, sAB=0.0, sB=16703151.659744, sX0=30645058.681189) 

1753# Intersector.All[2]: XDict(aAB=0.0, c=0, latA=-0.0, latB=-0.0, lonA=-30.16058, lonB=-30.16058, sA=-33941862.69597, sAB=0.0, sB=-3357460.370268, sX0=37299323.066238) 

1754# Intersector.All[3]: XDict(aAB=0.0, c=0, latA=-0.0, latB=0.0, lonA=150.046964, lonB=150.046964, sA=-13941907.021445, sAB=0.0, sB=-23371865.025835, sX0=37313772.047279) 

1755 

1756# % env PYGEODESY_INTERSECTTOOL=... python3 -m ....pygeodesy.geodesici -T -C -R 4e7 -c 50 -4 -147.7 0 0 90 

1757# Intersectool.All[0]: XDict(c=0, latA=-0.0, latB=-0.0, lonA=-29.745492, lonB=-29.745492, sA=6058048.653081, sAB=0.0, sB=-3311252.995823, sX0=9369301.648903) 

1758# Intersectool.All[1]: XDict(c=0, latA=0.0, latB=0.0, lonA=150.046964, lonB=150.046964, sA=-13941907.021445, sAB=0.0, sB=16703151.659744, sX0=30645058.681189) 

1759# Intersectool.All[2]: XDict(c=0, latA=-0.0, latB=-0.0, lonA=-30.16058, lonB=-30.16058, sA=-33941862.69597, sAB=0.0, sB=-3357460.370268, sX0=37299323.066238) 

1760# Intersectool.All[3]: XDict(c=0, latA=-0.0, latB=0.0, lonA=150.046964, lonB=150.046964, sA=-13941907.021445, sAB=0.0, sB=-23371865.025835, sX0=37313772.047279) 

1761 

1762# % python3 -m ....pygeodesy.geodesici -R 4e7 -i 0 0 10 10 50 -4 -50 -4 

1763# Intersector.All[0]: XDict(c=0, sA=-631414.26877, sB=5988887.278435, sX0=1866020.935315) 

1764# Intersector.All[1]: XDict(c=0, sA=19422725.117572, sB=-14062417.105648, sX0=38239422.83511) 

1765# Intersector.All[2]: XDict(c=0, sA=19422725.117572, sB=25945445.811603, sX0=39048781.218067) 

1766# Intersector.All[3]: XDict(c=0, sA=39476927.464575, sB=5894074.699478, sX0=39051612.452944) 

1767 

1768# % env PYGEODESY_INTERSECTTOOL=... python3 -m ....pygeodesy.geodesici -T -R 4e7 -i 0 0 10 10 50 -4 -50 -4 

1769# Intersectool.All[0]: XDict(c=0, sA=-631414.26877, sB=5988887.278435, sX0=1862009.05513) 

1770# Intersectool.All[1]: XDict(c=0, sA=19422725.117572, sB=-14062417.105648, sX0=38243434.715295) 

1771# Intersectool.All[2]: XDict(c=0, sA=19422725.117572, sB=25945445.811603, sX0=39044769.337882) 

1772# Intersectool.All[3]: XDict(c=0, sA=39476927.464575, sB=5894074.699478, sX0=39047600.57276) 

1773 

1774 

1775# **) MIT License 

1776# 

1777# Copyright (C) 2024-2025 -- mrJean1 at Gmail -- All Rights Reserved. 

1778# 

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

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

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

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

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

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

1785# 

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

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

1788# 

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

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

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

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

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

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

1795# OTHER DEALINGS IN THE SOFTWARE.