Coverage for pygeodesy/sphericalBase.py: 94%

251 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-11-12 13:23 -0500

1 

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

3 

4u'''(INTERNAL) Private spherical base classes C{CartesianSphericalBase} and 

5C{LatLonSphericalBase} for L{sphericalNvector} and L{sphericalTrigonometry}. 

6 

7A pure Python implementation of geodetic (lat-/longitude) functions, 

8transcoded in part from JavaScript originals by I{(C) Chris Veness 2011-2016} 

9and published under the same MIT Licence**, see 

10U{Latitude/Longitude<https://www.Movable-Type.co.UK/scripts/latlong.html>}. 

11''' 

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

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

14 

15from pygeodesy.basics import _copysign, isbool, isinstanceof, isscalar, map1 

16from pygeodesy.cartesianBase import CartesianBase, Bearing2Tuple 

17from pygeodesy.constants import EPS, EPS0, PI, PI2, PI_2, R_M, \ 

18 _0_0, _0_5, _1_0, _180_0, _360_0, \ 

19 _over, isnear0, isnon0 

20from pygeodesy.datums import Datums, _earth_ellipsoid, _spherical_datum 

21from pygeodesy.errors import IntersectionError, _ValueError, \ 

22 _xattr, _xError 

23from pygeodesy.fmath import favg, fdot, hypot, sqrt_a 

24from pygeodesy.interns import NN, _COMMA_, _concentric_, _datum_, \ 

25 _distant_, _exceed_PI_radians_, _name_, \ 

26 _near_, _radius_, _too_ 

27from pygeodesy.latlonBase import LatLonBase, _trilaterate5 # PYCHOK passed 

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

29# from pygeodesy.namedTuples import Bearing2Tuple # from .cartesianBase 

30from pygeodesy.nvectorBase import NvectorBase, Fmt, _xattrs 

31from pygeodesy.props import deprecated_method, property_doc_, \ 

32 property_RO, _update_all 

33# from pygeodesy.streprs import Fmt, _xattrs # from .nvectorBase 

34from pygeodesy.units import Bearing, Bearing_, Radians_, Radius, \ 

35 Radius_, Scalar_, _100km 

36from pygeodesy.utily import acos1, asin1, atan2b, atan2d, degrees90, \ 

37 degrees180, sincos2, sincos2d, _unrollon, \ 

38 tanPI_2_2, wrapPI 

39 

40from math import cos, fabs, log, sin, sqrt 

41 

42__all__ = _ALL_LAZY.sphericalBase 

43__version__ = '23.10.24' 

44 

45 

46class CartesianSphericalBase(CartesianBase): 

47 '''(INTERNAL) Base class for spherical C{Cartesian}s. 

48 ''' 

49 _datum = Datums.Sphere # L{Datum} 

50 

51 def intersections2(self, rad1, other, rad2, radius=R_M): 

52 '''Compute the intersection points of two circles each defined 

53 by a center point and a radius. 

54 

55 @arg rad1: Radius of the this circle (C{meter} or C{radians}, 

56 see B{C{radius}}). 

57 @arg other: Center of the other circle (C{Cartesian}). 

58 @arg rad2: Radius of the other circle (C{meter} or C{radians}, 

59 see B{C{radius}}). 

60 @kwarg radius: Mean earth radius (C{meter} or C{None} if both 

61 B{C{rad1}} and B{C{rad2}} are given in C{radians}). 

62 

63 @return: 2-Tuple of the intersection points, each C{Cartesian}. 

64 For abutting circles, the intersection points are the 

65 same C{Cartesian} instance, aka the I{radical center}. 

66 

67 @raise IntersectionError: Concentric, antipodal, invalid or 

68 non-intersecting circles. 

69 

70 @raise TypeError: If B{C{other}} is not C{Cartesian}. 

71 

72 @raise ValueError: Invalid B{C{rad1}}, B{C{rad2}} or B{C{radius}}. 

73 

74 @see: U{Calculating intersection of two Circles 

75 <https://GIS.StackExchange.com/questions/48937/ 

76 calculating-intersection-of-two-circles>} and method 

77 or function C{trilaterate3d2}. 

78 ''' 

79 x1, x2 = self, self.others(other) 

80 r1, r2, x = _rads3(rad1, rad2, radius) 

81 if x: 

82 x1, x2 = x2, x1 

83 try: 

84 n, q = x1.cross(x2), x1.dot(x2) 

85 n2, q1 = n.length2, (_1_0 - q**2) 

86 if n2 < EPS or isnear0(q1): 

87 raise ValueError(_near_(_concentric_)) 

88 c1, c2 = cos(r1), cos(r2) 

89 x0 = x1.times((c1 - q * c2) / q1).plus( 

90 x2.times((c2 - q * c1) / q1)) 

91 n1 = _1_0 - x0.length2 

92 if n1 < EPS: 

93 raise ValueError(_too_(_distant_)) 

94 except ValueError as x: 

95 raise IntersectionError(center=self, rad1=rad1, 

96 other=other, rad2=rad2, cause=x) 

97 n = n.times(sqrt(n1 / n2)) 

98 if n.length > EPS: 

99 x1 = x0.plus(n) 

100 x2 = x0.minus(n) 

101 else: # abutting circles 

102 x1 = x2 = x0 

103 

104 return (_xattrs(x1, self, _datum_, _name_), 

105 _xattrs(x2, self, _datum_, _name_)) 

106 

107 @property_RO 

108 def sphericalCartesian(self): 

109 '''Get this C{Cartesian}'s spherical class. 

110 ''' 

111 return type(self) 

112 

113 

114class LatLonSphericalBase(LatLonBase): 

115 '''(INTERNAL) Base class for spherical C{LatLon}s. 

116 ''' 

117 _datum = Datums.Sphere # spherical L{Datum} 

118 _napieradius = _100km 

119 

120 def __init__(self, latlonh, lon=None, height=0, datum=None, wrap=False, name=NN): 

121 '''Create a spherical C{LatLon} point frome the given lat-, longitude and 

122 height on the given datum. 

123 

124 @arg latlonh: Latitude (C{degrees} or DMS C{str} with N or S suffix) or 

125 a previous C{LatLon} instance provided C{B{lon}=None}. 

126 @kwarg lon: Longitude (C{degrees} or DMS C{str} with E or W suffix) or 

127 C(None), indicating B{C{latlonh}} is a C{LatLon}. 

128 @kwarg height: Optional height above (or below) the earth surface (C{meter}, 

129 same units as the datum's ellipsoid axes or radius). 

130 @kwarg datum: Optional, spherical datum to use (L{Datum}, L{Ellipsoid}, 

131 L{Ellipsoid2}, L{a_f2Tuple}) or earth radius in C{meter}, 

132 conventionally). 

133 @kwarg wrap: If C{True}, wrap or I{normalize} B{C{lat}} and B{C{lon}} 

134 (C{bool}). 

135 @kwarg name: Optional name (string). 

136 

137 @raise TypeError: If B{C{latlonh}} is not a C{LatLon} or B{C{datum}} not 

138 spherical. 

139 ''' 

140 LatLonBase.__init__(self, latlonh, lon=lon, height=height, wrap=wrap, name=name) 

141 if datum not in (None, self.datum): 

142 self.datum = datum 

143 

144 def bearingTo2(self, other, wrap=False, raiser=False): 

145 '''Return the initial and final bearing (forward and reverse 

146 azimuth) from this to an other point. 

147 

148 @arg other: The other point (C{LatLon}). 

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

150 B{C{other}} point (C{bool}). 

151 

152 @return: A L{Bearing2Tuple}C{(initial, final)}. 

153 

154 @raise TypeError: The B{C{other}} point is not spherical. 

155 

156 @see: Methods C{initialBearingTo} and C{finalBearingTo}. 

157 ''' 

158 # .initialBearingTo is inside .-Nvector and .-Trigonometry 

159 i = self.initialBearingTo(other, wrap=wrap, raiser=raiser) # PYCHOK .initialBearingTo 

160 f = self.finalBearingTo( other, wrap=wrap, raiser=raiser) 

161 return Bearing2Tuple(i, f, name=self.name) 

162 

163 @property_doc_(''' this point's datum (L{Datum}).''') 

164 def datum(self): 

165 '''Get this point's datum (L{Datum}). 

166 ''' 

167 return self._datum 

168 

169 @datum.setter # PYCHOK setter! 

170 def datum(self, datum): 

171 '''Set this point's datum I{without conversion} (L{Datum}, L{Ellipsoid}, 

172 L{Ellipsoid2}, L{a_f2Tuple}) or C{scalar} spherical earth radius). 

173 

174 @raise TypeError: If B{C{datum}} invalid or not not spherical. 

175 ''' 

176 d = _spherical_datum(datum, name=self.name, raiser=_datum_) 

177 if self._datum != d: 

178 _update_all(self) 

179 self._datum = d 

180 

181 def finalBearingTo(self, other, wrap=False, raiser=False): 

182 '''Return the final bearing (reverse azimuth) from this to 

183 an other point. 

184 

185 @arg other: The other point (spherical C{LatLon}). 

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

187 the B{C{other}} point (C{bool}). 

188 

189 @return: Final bearing (compass C{degrees360}). 

190 

191 @raise TypeError: The B{C{other}} point is not spherical. 

192 

193 @example: 

194 

195 >>> p = LatLon(52.205, 0.119) 

196 >>> q = LatLon(48.857, 2.351) 

197 >>> b = p.finalBearingTo(q) # 157.9 

198 ''' 

199 p = self.others(other) 

200 if wrap: 

201 p = _unrollon(self, p, wrap=wrap) 

202 # final bearing is the reverse of the other, initial one 

203 b = p.initialBearingTo(self, wrap=False, raiser=raiser) + _180_0 

204 return b if b < 360 else (b - _360_0) 

205 

206 def intersecant2(self, circle, point, other, radius=R_M, exact=False, # PYCHOK signature 

207 height=None, wrap=False): 

208 '''Compute the intersections of a circle and a (great circle) line 

209 given as two points or as a point and bearing. 

210 

211 @arg circle: Radius of the circle centered at this location (C{meter}, 

212 same units as B{C{radius}}) or a point on the circle 

213 (this C{LatLon}). 

214 @arg point: A point on the (great circle) line (this C{LatLon}). 

215 @arg other: An other point I{on} (this {LatLon}) or the bearing at 

216 B{C{point}} I{of} the (great circle) line (compass 

217 C{degrees}). 

218 @kwarg radius: Mean earth radius (C{meter}, conventionally). 

219 @kwarg exact: If C{True} use the I{exact} rhumb methods for azimuth, 

220 destination and distance, if C{False} use the basic 

221 rhumb methods (C{bool}) or if C{None} use the I{great 

222 circle} methods. 

223 @kwarg height: Optional height for the intersection points (C{meter}, 

224 conventionally) or C{None} for interpolated heights. 

225 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the points 

226 B{C{circle}}, B{C{point}} and/or B{C{other}} (C{bool}). 

227 

228 @return: 2-Tuple of the intersection points (representing a chord), each 

229 an instance of the B{C{point}} class. Both points are the same 

230 instance if the (great circle) line is tangent to the circle. 

231 

232 @raise IntersectionError: The circle and line do not intersect. 

233 

234 @raise TypeError: If B{C{point}} is not this C{LatLon} or B{C{circle}} 

235 or B{C{other}} invalid. 

236 

237 @raise UnitError: Invalid B{C{circle}}, B{C{other}}, B{C{radius}}, 

238 B{C{exact}}, B{C{height}} or B{C{napieradius}}. 

239 ''' 

240 p = self.others(point=point) 

241 try: 

242 return _intersecant2(self, circle, p, other, radius=radius, exact=exact, 

243 height=height, wrap=wrap) 

244 except (TypeError, ValueError) as x: 

245 raise _xError(x, center=self, circle=circle, point=point, other=other, 

246 radius=radius, exact=exact, height=height, wrap=wrap) 

247 

248 def maxLat(self, bearing): 

249 '''Return the maximum latitude reached when travelling 

250 on a great circle on given bearing from this point 

251 based on Clairaut's formula. 

252 

253 The maximum latitude is independent of longitude 

254 and the same for all points on a given latitude. 

255 

256 Negate the result for the minimum latitude (on the 

257 Southern hemisphere). 

258 

259 @arg bearing: Initial bearing (compass C{degrees360}). 

260 

261 @return: Maximum latitude (C{degrees90}). 

262 

263 @raise ValueError: Invalid B{C{bearing}}. 

264 ''' 

265 m = acos1(fabs(sin(Bearing_(bearing)) * cos(self.phi))) 

266 return degrees90(m) 

267 

268 def minLat(self, bearing): 

269 '''Return the minimum latitude reached when travelling 

270 on a great circle on given bearing from this point. 

271 

272 @arg bearing: Initial bearing (compass C{degrees360}). 

273 

274 @return: Minimum latitude (C{degrees90}). 

275 

276 @see: Method L{maxLat} for more details. 

277 

278 @raise ValueError: Invalid B{C{bearing}}. 

279 ''' 

280 return -self.maxLat(bearing) 

281 

282 def _mpr(self, radius=R_M, exact=None): # meter per radian 

283 if exact and not isscalar(radius): # see .rhumbx.Rhumb._mpr 

284 radius = _earth_ellipsoid(radius)._Lpr 

285 return radius 

286 

287 @property_doc_(''' the I{Napier} radius to apply spherical trigonometry.''') 

288 def napieradius(self): 

289 '''Get the I{Napier} radius (C{meter}, conventionally). 

290 ''' 

291 return self._napieradius 

292 

293 @napieradius.setter # PYCHOK setter! 

294 def napieradius(self, radius): 

295 '''Set this I{Napier} radius (C{meter}, conventionally) or C{0}. 

296 

297 In methods L{intersecant2} and L{rhumbIntersecant2}, I{Napier}'s 

298 spherical trigonometry is applied if the circle radius exceeds 

299 the I{Napier} radius, otherwise planar trigonometry is used. 

300 

301 @raise UnitError: Invalid B{C{radius}}. 

302 ''' 

303 self._napieradius = Radius(napieradius=radius or 0) 

304 

305# def nearestTo(self, point, other, **radius_exact_height_wrap): # PYCHOK signature 

306# p = self.others(point=point) 

307# try: 

308# p, q = _intersecant2(self, p, p, other, **radius_exact_height_wrap) 

309# except (TypeError, ValueError) as x: 

310# raise _xError(x, this=self, point=point, other=other, **radius_exact_height_wrap) 

311# return p.midpointTo(q) 

312 

313 def parse(self, strllh, height=0, sep=_COMMA_, name=NN): 

314 '''Parse a string representing a similar, spherical C{LatLon} 

315 point, consisting of C{"lat, lon[, height]"}. 

316 

317 @arg strllh: Lat, lon and optional height (C{str}), 

318 see function L{pygeodesy.parse3llh}. 

319 @kwarg height: Optional, default height (C{meter}). 

320 @kwarg sep: Optional separator (C{str}). 

321 @kwarg name: Optional instance name (C{str}), 

322 overriding this name. 

323 

324 @return: The similar point (spherical C{LatLon}). 

325 

326 @raise ParseError: Invalid B{C{strllh}}. 

327 ''' 

328 t = _MODS.dms.parse3llh(strllh, height=height, sep=sep) 

329 r = self.classof(*t) 

330 if name: 

331 r.rename(name) 

332 return r 

333 

334 @property_RO 

335 def _radius(self): 

336 '''(INTERNAL) Get this sphere's radius. 

337 ''' 

338 return self.datum.ellipsoid.equatoradius 

339 

340 def _rhumbs3(self, other, wrap, r=False): # != .latlonBase._rhumbx3 

341 '''(INTERNAL) Rhumb_ helper function. 

342 

343 @arg other: The other point (spherical C{LatLon}). 

344 ''' 

345 p = self.others(other, up=2) 

346 if wrap: 

347 p = _unrollon(self, p, wrap=wrap) 

348 a2, b2 = p.philam 

349 a1, b1 = self.philam 

350 # if |db| > 180 take shorter rhumb 

351 # line across the anti-meridian 

352 db = wrapPI(b2 - b1) 

353 dp = _logPI_2_2(a2, a1) 

354 da = a2 - a1 

355 if r: 

356 # on Mercator projection, longitude distances shrink 

357 # by latitude; the 'stretch factor' q becomes ill- 

358 # conditioned along E-W line (0/0); use an empirical 

359 # tolerance to avoid it 

360 q = (da / dp) if fabs(dp) > EPS else cos(a1) 

361 da = hypot(da, q * db) # angular distance radians 

362 return da, db, dp 

363 

364 def rhumbAzimuthTo(self, other, radius=R_M, exact=False, wrap=False, b360=False): 

365 '''Return the azimuth (bearing) of a rhumb line (loxodrome) between 

366 this and an other (spherical) point. 

367 

368 @arg other: The other point (spherical C{LatLon}). 

369 @kwarg radius: Earth radius (C{meter}) or earth model (L{Datum}, 

370 L{Ellipsoid}, L{Ellipsoid2} or L{a_f2Tuple}). 

371 @kwarg exact: If C{True}, use I{Krüger} L{rhumbx} (C{bool}), 

372 default C{False} for backward compatibility. 

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

374 B{C{other}} point (C{bool}). 

375 @kwarg b360: If C{True}, return the azimuth in the bearing range. 

376 

377 @return: Rhumb azimuth (compass C{degrees180} or C{degrees360}). 

378 

379 @raise TypeError: The B{C{other}} point is incompatible or 

380 B{C{radius}} is invalid. 

381 

382 @example: 

383 

384 >>> p = LatLon(51.127, 1.338) 

385 >>> q = LatLon(50.964, 1.853) 

386 >>> b = p.rhumbBearingTo(q) # 116.7 

387 ''' 

388 if exact: # use series, always 

389 z = LatLonBase.rhumbAzimuthTo(self, other, exact=False, # Krüger 

390 radius=radius, wrap=wrap, b360=b360) 

391 else: 

392 _, db, dp = self._rhumbs3(other, wrap) 

393 z = (atan2b if b360 else atan2d)(db, dp) # see .rhumbBase.RhumbBase.Inverse 

394 return z 

395 

396 @deprecated_method 

397 def rhumbBearingTo(self, other): # unwrapped 

398 '''DEPRECATED, use method C{.rhumbAzimuthTo}.''' 

399 return self.rhumbAzimuthTo(other, b360=True) # [0..360) 

400 

401 def rhumbDestination(self, distance, azimuth, radius=R_M, height=None, exact=False): 

402 '''Return the destination point having travelled the given distance from 

403 this point along a rhumb line (loxodrome) of the given azimuth. 

404 

405 @arg distance: Distance travelled (C{meter}, same units as B{C{radius}}), 

406 may be negative if C{B{exact}=True}. 

407 @arg azimuth: Azimuth (bearing) of the rhumb line (compass C{degrees}). 

408 @kwarg radius: Earth radius (C{meter}) or earth model (L{Datum}, 

409 L{Ellipsoid}, L{Ellipsoid2} or L{a_f2Tuple}) if 

410 C{B{exact}=True}. 

411 @kwarg height: Optional height, overriding the default height (C{meter}. 

412 @kwarg exact: If C{True}, use I{Krüger} L{rhumbx} (C{bool}), default 

413 C{False} for backward compatibility. 

414 

415 @return: The destination point (spherical C{LatLon}). 

416 

417 @raise ValueError: Invalid B{C{distance}}, B{C{azimuth}}, B{C{radius}} 

418 or B{C{height}}. 

419 

420 @example: 

421 

422 >>> p = LatLon(51.127, 1.338) 

423 >>> q = p.rhumbDestination(40300, 116.7) # 50.9642°N, 001.8530°E 

424 ''' 

425 if exact: # use series, always 

426 r = LatLonBase.rhumbDestination(self, distance, azimuth, exact=False, # Krüger 

427 radius=radius, height=height) 

428 else: # radius=None from .rhumbMidpointTo 

429 if radius in (None, self._radius): 

430 d, r = self.datum, radius 

431 else: 

432 d = _spherical_datum(radius, raiser=_radius_) # spherical only 

433 r = d.ellipsoid.equatoradius 

434 r = _m2radians(distance, r, low=-EPS) # distance=0 from .rhumbMidpointTo 

435 

436 a1, b1 = self.philam 

437 sb, cb = sincos2(Bearing_(azimuth)) # radians 

438 

439 da = r * cb 

440 a2 = a1 + da 

441 # normalize latitude if past pole 

442 if fabs(a2) > PI_2: 

443 a2 = _copysign(PI, a2) - a2 

444 

445 dp = _logPI_2_2(a2, a1) 

446 # q becomes ill-conditioned on E-W course 0/0 

447 q = cos(a1) if isnear0(dp) else (da / dp) 

448 b2 = b1 if isnear0(q) else (b1 + r * sb / q) 

449 

450 h = self._heigHt(height) 

451 r = self.classof(degrees90(a2), degrees180(b2), datum=d, height=h) 

452 return r 

453 

454 def rhumbDistanceTo(self, other, radius=R_M, exact=False, wrap=False): 

455 '''Return the distance from this to an other point along 

456 a rhumb line (loxodrome). 

457 

458 @arg other: The other point (spherical C{LatLon}). 

459 @kwarg radius: Earth radius (C{meter}) or earth model (L{Datum}, 

460 L{Ellipsoid}, L{Ellipsoid2} or L{a_f2Tuple}) if 

461 C{B{exact}=True}. 

462 @kwarg exact: If C{True}, use I{Krüger} L{rhumbx} (C{bool}), 

463 default C{False} for backward compatibility. 

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

465 B{C{other}} point (C{bool}). 

466 

467 @return: Distance (C{meter}, the same units as B{C{radius}} 

468 or C{radians} if B{C{radius}} is C{None}). 

469 

470 @raise TypeError: The B{C{other}} point is incompatible. 

471 

472 @raise ValueError: Invalid B{C{radius}}. 

473 

474 @example: 

475 

476 >>> p = LatLon(51.127, 1.338) 

477 >>> q = LatLon(50.964, 1.853) 

478 >>> d = p.rhumbDistanceTo(q) # 403100 

479 ''' 

480 if exact: # use series, always 

481 r = LatLonBase.rhumbDistanceTo(self, other, exact=False, # Krüger 

482 radius=radius, wrap=wrap) 

483 if radius is None: # angular distance in radians 

484 r = r / self._radius # /= chokes PyChecker 

485 else: 

486 # see <https://www.EdWilliams.org/avform.htm#Rhumb> 

487 r, _, _ = self._rhumbs3(other, wrap, r=True) 

488 if radius is not None: 

489 r *= Radius(radius) 

490 return r 

491 

492 def rhumbIntersecant2(self, circle, point, other, radius=R_M, exact=True, # PYCHOK signature 

493 height=None, wrap=False): 

494 '''Compute the intersections of a circle and a rhumb line given as two 

495 points and as a point and azimuth. 

496 

497 @arg circle: Radius of the circle centered at this location (C{meter}, 

498 same units as B{C{radius}}) or a point on the circle 

499 (this C{LatLon}). 

500 @arg point: The rhumb line's start point (this C{LatLon}). 

501 @arg other: An other point (this I{on} C{LatLon}) or the azimuth I{of} 

502 (compass C{degrees}) the rhumb line. 

503 @kwarg radius: Mean earth radius (C{meter}, conventionally). 

504 @kwarg exact: If C{True} use the I{exact} rhumb methods for azimuth, 

505 destination and distance, if C{False} use the basic 

506 rhumb methods (C{bool}) or if C{None} use the I{great 

507 circle} methods. 

508 @kwarg height: Optional height for the intersection points (C{meter}, 

509 conventionally) or C{None}. 

510 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll the points 

511 B{C{circle}}, B{C{point}} and/or B{C{other}} (C{bool}). 

512 

513 @return: 2-Tuple of the intersection points (representing a chord), 

514 each an instance of this class. For a tangent line, both 

515 points are the same instance, wrapped or I{normalized}. 

516 

517 @raise IntersectionError: The circle and line do not intersect. 

518 

519 @raise TypeError: If B{C{point}} is not this C{LatLon} or B{C{circle}} 

520 or B{C{other}} invalid. 

521 

522 @raise UnitError: Invalid B{C{circle}}, B{C{other}}, B{C{radius}}, 

523 B{C{exact}} or B{C{height}}. 

524 ''' 

525 m = LatLonBase.rhumbIntersecant2 if exact else \ 

526 LatLonSphericalBase.intersecant2 

527 return m(self, circle, point, other, radius=radius, exact=exact, 

528 height=height, wrap=wrap) 

529 

530 def rhumbMidpointTo(self, other, height=None, radius=R_M, exact=False, 

531 fraction=_0_5, wrap=False): 

532 '''Return the (loxodromic) midpoint on the rhumb line between 

533 this and an other point. 

534 

535 @arg other: The other point (spherical LatLon). 

536 @kwarg height: Optional height, overriding the mean height 

537 (C{meter}). 

538 @kwarg radius: Earth radius (C{meter}) or earth model (L{Datum}, 

539 L{Ellipsoid}, L{Ellipsoid2} or L{a_f2Tuple}). 

540 @kwarg exact: If C{True}, use I{Krüger} L{rhumbx} (C{bool}), 

541 default C{False} for backward compatibility. 

542 @kwarg fraction: Midpoint location from this point (C{scalar}), 

543 may be negative if C{B{exact}=True}. 

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

545 B{C{other}} point (C{bool}). 

546 

547 @return: The (mid)point at the given B{C{fraction}} along 

548 the rhumb line (spherical C{LatLon}). 

549 

550 @raise TypeError: The B{C{other}} point is incompatible. 

551 

552 @raise ValueError: Invalid B{C{height}} or B{C{fraction}} 

553 

554 @example: 

555 

556 >>> p = LatLon(51.127, 1.338) 

557 >>> q = LatLon(50.964, 1.853) 

558 >>> m = p.rhumb_midpointTo(q) 

559 >>> m.toStr() # '51.0455°N, 001.5957°E' 

560 ''' 

561 if exact: # use series, always 

562 r = LatLonBase.rhumbMidpointTo(self, other, exact=False, # Krüger 

563 radius=radius, height=height, 

564 fraction=fraction, wrap=wrap) 

565 elif fraction is not _0_5: 

566 f = Scalar_(fraction=fraction) # low=_0_0 

567 r, db, dp = self._rhumbs3(other, wrap, r=True) # radians 

568 z = atan2b(db, dp) 

569 h = self._havg(other, f=f, h=height) 

570 r = self.rhumbDestination(r * f, z, radius=None, height=h) 

571 

572 else: # for backward compatibility, unwrapped 

573 # see <https://MathForum.org/library/drmath/view/51822.html> 

574 a1, b1 = self.philam 

575 a2, b2 = self.others(other).philam 

576 

577 if fabs(b2 - b1) > PI: 

578 b1 += PI2 # crossing anti-meridian 

579 

580 a3 = favg(a1, a2) 

581 b3 = favg(b1, b2) 

582 

583 f1 = tanPI_2_2(a1) 

584 if isnon0(f1): 

585 f2 = tanPI_2_2(a2) 

586 f = f2 / f1 

587 if isnon0(f): 

588 f = log(f) 

589 if isnon0(f): 

590 f3 = tanPI_2_2(a3) 

591 b3 = fdot(map1(log, f1, f2, f3), 

592 -b2, b1, b2 - b1) / f 

593 

594 d = self.datum if radius in (None, self._radius) else \ 

595 _spherical_datum(radius, name=self.name, raiser=_radius_) 

596 h = self._havg(other, h=height) 

597 r = self.classof(degrees90(a3), degrees180(b3), datum=d, height=h) 

598 return r 

599 

600 @property_RO 

601 def sphericalLatLon(self): 

602 '''Get this C{LatLon}'s spherical class. 

603 ''' 

604 return type(self) 

605 

606 def toNvector(self, Nvector=NvectorBase, **Nvector_kwds): # PYCHOK signature 

607 '''Convert this point to C{Nvector} components, I{including 

608 height}. 

609 

610 @kwarg Nvector_kwds: Optional, additional B{C{Nvector}} 

611 keyword arguments, ignored if 

612 C{B{Nvector} is None}. 

613 

614 @return: An B{C{Nvector}} or a L{Vector4Tuple}C{(x, y, z, h)} 

615 if B{C{Nvector}} is C{None}. 

616 

617 @raise TypeError: Invalid B{C{Nvector}} or B{C{Nvector_kwds}}. 

618 ''' 

619 return LatLonBase.toNvector(self, Nvector=Nvector, **Nvector_kwds) 

620 

621 

622def _intersecant2(c, r, p, b, radius=R_M, exact=False, height=None, wrap=False): 

623 # (INTERNAL) Intersect a circle and line, see L{intersecant2} 

624 # above, separated to allow callers to embellish any exceptions 

625 

626 if wrap: 

627 p = _unrollon(c, p, wrap=wrap) 

628 nonexact = exact is None 

629 

630 if not isinstanceof(r, c.__class__, p.__class__): 

631 r = Radius_(circle=r) 

632 elif nonexact: 

633 r = c.distanceTo(r, radius=radius, wrap=wrap) 

634 elif isbool(exact): 

635 r = c.rhumbDistanceTo(r, radius=radius, exact=exact, wrap=wrap) 

636 else: 

637 raise _ValueError(exact=exact) 

638 

639 if not isinstanceof(b, c.__class__, p.__class__): 

640 b = Bearing(b) 

641 elif nonexact: 

642 b = p.initialBearingTo(b, wrap=wrap) 

643 else: 

644 b = p.rhumbAzimuthTo(b, radius=radius, exact=exact, wrap=wrap, 

645 b360=True) 

646 

647 d = p.distanceTo(c, radius=radius) if nonexact else \ 

648 p.rhumbDistanceTo(c, radius=radius, exact=exact) 

649 if d > EPS0: 

650 n = _xattr(c, napieradius=0) 

651 a = p.initialBearingTo(c) if nonexact else \ 

652 p.rhumbAzimuthTo(c, radius=radius, exact=exact, b360=True) 

653 s, c = sincos2d(b - a) # Napier's sin(A), cos(A) 

654 if r > n: 

655 # Napier's right spherical triangle rules (R2) and (R1) 

656 # <https://WikiPedia.org/wiki/Spherical_trigonometry> 

657 m = p._mpr(radius=radius, exact=exact) # meter per radian 

658 if fabs(c) > EPS0: 

659 d = d / m # /= chokes PyChecker 

660 a = asin1(sin(d) * fabs(s)) # Napier's a 

661 c = _copysign(cos(a), c) 

662 d = acos1(cos(d) / c) * m 

663 a *= m # meter 

664 else: # point and chord center coincident 

665 a, d = d, 0 

666 c = cos(a / m) 

667 h = (acos1(cos(r / m) / c) * m) if a < r else 0 

668 else: # distance from the chord center to ... 

669 a = fabs(d * s) # ... the cicle center ... 

670 d *= c # ... and to the point 

671 h = sqrt_a(r, a) if a < r else 0 # half chord length 

672 if a > r: 

673 raise IntersectionError(_too_(Fmt.distant(a))) 

674 else: 

675 d, h = 0, r # point and circle center coincident 

676 

677 _intersecant1, kwds = (p.destination, {}) if nonexact else \ 

678 (p.rhumbDestination, dict(exact=exact)) 

679 kwds.update(radius=radius, height=height) 

680 t = (_intersecant1(d + h, b, **kwds),) 

681 if h: 

682 t += (_intersecant1(d - h, b, **kwds),) 

683 else: # same instance twice 

684 t *= 2 

685 return t 

686 

687 

688def _logPI_2_2(a2, a1): 

689 '''(INTERNAL) C{log} of C{tanPI_2_2}'s quotient. 

690 ''' 

691 return log(_over(tanPI_2_2(a2), tanPI_2_2(a1))) 

692 

693 

694def _m2radians(distance, radius, low=EPS): # PYCHOK in .spherical* 

695 '''(INTERNAL) Distance in C{meter} to angular distance in C{radians}. 

696 

697 @raise UnitError: Invalid B{C{distance}} or B{C{radius}}. 

698 ''' 

699 r = float(distance) 

700 if radius: 

701 r = r / Radius_(radius=radius) # /= chokes PyChecker 

702 if low is not None: 

703 # small near0 values from .rhumbDestination not exact OK 

704 r = _0_0 if low < 0 and r < 0 else Radians_(r, low=low) 

705 # _0_0 if low < 0 and low < r < 0 else Radians_(r, low=low) 

706 return r 

707 

708 

709def _radians2m(rad, radius): 

710 '''(INTERNAL) Angular distance in C{radians} to distance in C{meter}. 

711 ''' 

712 if radius is not None: # not in (None, _0_0) 

713 rad *= R_M if radius is R_M else Radius(radius) 

714 return rad 

715 

716 

717def _rads3(rad1, rad2, radius): # in .sphericalTrigonometry 

718 '''(INTERNAL) Convert radii to radians. 

719 ''' 

720 r1 = Radius_(rad1=rad1) 

721 r2 = Radius_(rad2=rad2) 

722 if radius is not None: # convert radii to radians 

723 r1 = _m2radians(r1, radius) 

724 r2 = _m2radians(r2, radius) 

725 

726 x = r1 < r2 

727 if x: 

728 r1, r2 = r2, r1 

729 if r1 > PI: 

730 raise IntersectionError(rad1=rad1, rad2=rad2, 

731 txt=_exceed_PI_radians_) 

732 return r1, r2, x 

733 

734 

735__all__ += _ALL_DOCS(CartesianSphericalBase, LatLonSphericalBase) 

736 

737# **) MIT License 

738# 

739# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved. 

740# 

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

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

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

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

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

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

747# 

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

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

750# 

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

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

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

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

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

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

757# OTHER DEALINGS IN THE SOFTWARE.