Coverage for pygeodesy/sphericalBase.py: 94%

1

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

3

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

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

6

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

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

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

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

11'''

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

13 from __future__ import division as _; del _ # noqa: E702 ;

14

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

16 from pygeodesy.cartesianBase import CartesianBase

17 from 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

20 from pygeodesy.datums import Datums, _earth_ellipsoid, _spherical_datum

21 from pygeodesy.errors import IntersectionError, _ValueError, \

22 _xattr, _xattrs, _xError

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

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

25 _exceed_PI_radians_, _name_, _near_, \

26 _radius_, _too_

27 from pygeodesy.latlonBase import LatLonBase

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

29# from pygeodesy.namedTuples import Bearing2Tuple # _MODS

30 from pygeodesy.nvectorBase import NvectorBase, Fmt

31 from pygeodesy.props import deprecated_method, property_doc_, property_RO, \

32 _update_all

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

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

35 Radius_, Scalar_, _100km

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

37 degrees180, sincos2, sincos2d, _unrollon, \

38 tanPI_2_2, wrapPI

39

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

41

42 __all__ = _ALL_LAZY.sphericalBase

43 __version__ = '25.05.26'

44

45

46 class 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

114 class 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):

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 radius or axes).

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

131 L{Ellipsoid2}, L{a_f2Tuple}) or the mean earth radius

132 (C{meter}, 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 C{B{name}=NN} (C{str}).

136

137 @raise TypeError: Invalid B{C{latlonh}} or B{C{datum}} not spherical.

138 '''

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

140 if not _isin(datum, None, self.datum):

141 self.datum = datum

142

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

144 '''Return the initial and final bearing (forward and reverse azimuth)

145 from this to an other point.

146

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

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

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

150

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

152

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

154

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

156 '''

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

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

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

160 return _MODS.namedTuples.Bearing2Tuple(i, f, name=self.name)

161

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

163 def datum(self):

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

165 '''

166 return self._datum

167

168 @datum.setter # PYCHOK setter!

169 def datum(self, datum):

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

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

172

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

174 '''

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

176 if self._datum != d:

177 _update_all(self)

178 self._datum = d

179

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

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

182 an other point.

183

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

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

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

187

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

189

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

191 '''

192 p = self.others(other)

193 if wrap:

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

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

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

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

198

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

200 height=None, wrap=False):

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

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

203

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

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

206 (same C{LatLon} class).

207 @arg point: A point on the (great circle) line (same C{LatLon} class).

208 @arg other: An other point I{on} (same C{LatLon} class) or the bearing

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

210 C{degrees}).

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

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

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

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

215 circle} methods.

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

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

218 @kwarg wrap: If C{True}, wrap or I{normalize} and unroll B{C{circle}},

219 B{C{point}} and B{C{other}} iff points (C{bool}).

220

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

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

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

224

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

226

227 @raise TypeError: Invalid B{C{point}}, B{C{circle}} or B{C{other}}.

228

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

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

231 '''

232 p = self.others(point=point)

233 try:

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

235 height=height, wrap=wrap)

236 except (TypeError, ValueError) as x:

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

238 radius=radius, exact=exact, height=height, wrap=wrap)

239

240 def maxLat(self, bearing):

241 '''Return the maximum latitude reached when travelling on a great circle

242 on given bearing from this point based on Clairaut's formula.

243

244 The maximum latitude is independent of longitude and the same for all

245 points on a given latitude.

246

247 Negate the result for the minimum latitude (on the Southern hemisphere).

248

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

250

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

252

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

254 '''

255 r = acos1(fabs(sin(Bearing_(bearing)) * cos(self.phi)))

256 return degrees90(r)

257

258 def minLat(self, bearing):

259 '''Return the minimum latitude reached when travelling on a great circle

260 on given bearing from this point.

261

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

263

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

265

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

267

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

269 '''

270 return -self.maxLat(bearing)

271

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

273 if exact and not _isRadius(radius): # see .rhumb.ekx.Rhumb._mpr

274 radius = _earth_ellipsoid(radius)._Lpr

275 return radius

276

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

278 def napieradius(self):

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

280 '''

281 return self._napieradius

282

283 @napieradius.setter # PYCHOK setter!

284 def napieradius(self, radius):

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

286

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

288 spherical trigonometry is applied if the circle radius exceeds

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

290

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

292 '''

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

294

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

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

297# try:

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

299# except (TypeError, ValueError) as x:

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

301# return p.midpointTo(q)

302

303 def parse(self, strllh, height=0, sep=_COMMA_, **name):

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

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

306

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

308 L{pygeodesy.parse3llh}.

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

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

311 @kwarg name: Optional C{B{name}=NN} (C{str}), overriding this name.

312

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

314

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

316 '''

317 llh = _MODS.dms.parse3llh(strllh, height=height, sep=sep)

318 return self.classof(*llh, **name)

319

320 @property_RO

321 def _radius(self):

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

323 '''

324 return self.datum.ellipsoid.equatoradius

325

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

327 '''(INTERNAL) Rhumb_ helper function.

328

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

330 '''

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

332 if wrap:

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

334 a2, b2 = p.philam

335 a1, b1 = self.philam

336 # if |db| > 180 take shorter rhumb

337 # line across the anti-meridian

338 db = wrapPI(b2 - b1)

339 dp = _logPI_2_2(a2, a1)

340 da = a2 - a1

341 if r:

342 # on Mercator projection, longitude distances shrink

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

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

345 # tolerance to avoid it

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

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

348 return da, db, dp

349

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

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

352 this and an other (spherical) point.

353

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

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

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

357 @kwarg exact: If C{True}, use I{Elliptic, Krüger} L{Rhumb} (C{bool}),

358 default C{False} for backward compatibility.

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

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

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

362

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

364

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

366 B{C{radius}} is invalid.

367 '''

368 if exact: # use series, always

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

370 radius=radius, wrap=wrap, b360=b360)

371 else:

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

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

374 return z

375

376 @deprecated_method

377 def rhumbBearingTo(self, other): # unwrapped

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

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

380

381 def rhumbDestination(self, distance, azimuth, radius=R_M, height=None,

382 exact=False, **name):

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

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

385

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

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

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

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

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

391 C{B{exact}=True}.

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

393 @kwarg exact: If C{True}, use I{Elliptic, Krüger} L{Rhumb} (C{bool}),

394 default C{False} for backward compatibility.

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

396

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

398

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

400 or B{C{height}}.

401 '''

402 if exact: # use series, always

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

404 radius=radius, height=height, **name)

405 else: # radius=None from .rhumbMidpointTo

406 if _isin(radius, None, self._radius):

407 d, r = self.datum, radius

408 else:

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

410 r = d.ellipsoid.equatoradius

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

412

413 a1, b1 = self.philam

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

415

416 da = r * cb

417 a2 = a1 + da

418 # normalize latitude if past pole

419 if fabs(a2) > PI_2:

420 a2 = _copysign(PI, a2) - a2

421

422 dp = _logPI_2_2(a2, a1)

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

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

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

426

427 h = self._heigHt(height)

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

429 return r

430

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

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

433 a rhumb line (loxodrome).

434

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

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

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

438 C{B{exact}=True}.

439 @kwarg exact: If C{True}, use I{Elliptic, Krüger} L{Rhumb} (C{bool}),

440 default C{False} for backward compatibility.

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

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

443

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

445 C{radians} if C{B{radius} is None}).

446

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

448

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

450 '''

451 if exact: # use series, always

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

453 radius=radius, wrap=wrap)

454 if radius is None: # angular distance in radians

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

456 else:

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

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

459 if radius is not None:

460 r *= Radius(radius)

461 return r

462

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

464 height=None, wrap=False):

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

466 points and as a point and azimuth.

467

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

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

470 (same C{LatLon} class).

471 @arg point: The rhumb line's start point (same C{LatLon} class).

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

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

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

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

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

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

478 circle} methods.

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

480 conventionally) or C{None}.

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

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

483

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

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

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

487

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

489

490 @raise TypeError: Invalid B{C{point}}, B{C{circle}} or B{C{other}}.

491

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

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

494 '''

495 m = LatLonBase.rhumbIntersecant2 if exact else \

496 LatLonSphericalBase.intersecant2

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

498 height=height, wrap=wrap)

499

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

501 fraction=_0_5, **wrap_name):

502 '''Return the (loxodromic) midpoint on the rhumb line between this

503 and an other point.

504

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

506 @kwarg height: Optional height, overriding the mean height (C{meter}).

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

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

509 @kwarg exact: If C{True}, use I{Elliptic, Krüger} L{Rhumb} (C{bool}),

510 default C{False} for backward compatibility.

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

512 be negative if C{B{exact}=True}.

513 @kwarg wrap_name: Optional C{B{name}=NN} (C{str}) and optional keyword

514 argument C{B{wrap}=False}, if C{True}, wrap or I{normalize}

515 and unroll the B{C{other}} point (C{bool}).

516

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

518 line (spherical C{LatLon}).

519

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

521

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

523 '''

524 if exact: # use series, always

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

526 radius=radius, height=height,

527 fraction=fraction, **wrap_name)

528 elif fraction is not _0_5:

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

530 w, n = self._wrap_name2(**wrap_name)

531 r, db, dp = self._rhumbs3(other, w, r=True) # radians

532 z = atan2b(db, dp)

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

534 r = self.rhumbDestination(r * f, z, radius=None, height=h, name=n)

535

536 else: # for backward compatibility, unwrapped

537 _, n = self._wrap_name2(**wrap_name)

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

539 a1, b1 = self.philam

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

541 _, n = self._wrap_name2(**wrap_name)

542

543 if fabs(b2 - b1) > PI:

544 b1 += PI2 # crossing anti-meridian

545

546 a3 = favg(a1, a2)

547 b3 = favg(b1, b2)

548

549 f1 = tanPI_2_2(a1)

550 if isnon0(f1):

551 f2 = tanPI_2_2(a2)

552 f = f2 / f1

553 if isnon0(f):

554 f = log(f)

555 if isnon0(f):

556 f3 = tanPI_2_2(a3)

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

558 -b2, b1, b2 - b1) / f

559

560 d = self.datum if _isin(radius, None, self._radius) else \

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

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

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

564 return r

565

566 @property_RO

567 def sphericalLatLon(self):

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

569 '''

570 return type(self)

571

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

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

574 height}.

575

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

577 arguments, ignored if C{B{Nvector} is None}.

578

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

580 B{C{Nvector} is None}.

581

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

583 '''

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

585

586

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

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

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

590

591 if wrap:

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

593 nonexact = exact is None

594

595 if not isinstanceof(r, type(c), type(p)):

596 r = Radius_(circle=r)

597 elif nonexact:

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

599 elif isbool(exact):

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

601 else:

602 raise _ValueError(exact=exact)

603

604 if not isinstanceof(b, type(c), type(p)):

605 b = Bearing(b)

606 elif nonexact:

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

608 else:

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

610 b360=True)

611

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

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

614 if d > EPS0:

615 n = _xattr(c, napieradius=0)

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

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

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

619 if r > n:

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

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

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

623 if fabs(c) > EPS0:

624 d = d / m # /= chokes PyChecker

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

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

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

628 a *= m # meter

629 else: # point and chord center coincident

630 a, d = d, 0

631 c = cos(a / m)

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

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

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

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

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

637 if a > r:

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

639 else:

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

641

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

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

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

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

646 if h:

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

648 else: # same instance twice

649 t *= 2

650 return t

651

652

653 def _logPI_2_2(a2, a1):

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

655 '''

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

657

658

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

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

661

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

663 '''

664 r = float(distance)

665 if radius:

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

667 if low is not None:

668 # small near0 values from .rhumbDestination not exact OK

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

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

671 return r

672

673

674 def _radians2m(rad, radius):

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

676 '''

677 if radius is not None: # not _isin(radius, None, _0_0)

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

679 return rad

680

681

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

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

684 '''

685 r1 = Radius_(rad1=rad1)

686 r2 = Radius_(rad2=rad2)

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

688 r1 = _m2radians(r1, radius)

689 r2 = _m2radians(r2, radius)

690

691 x = r1 < r2

692 if x:

693 r1, r2 = r2, r1

694 if r1 > PI:

695 raise IntersectionError(rad1=rad1, rad2=rad2,

696 txt=_exceed_PI_radians_)

697 return r1, r2, x

698

699

700 __all__ += _ALL_DOCS(CartesianSphericalBase, LatLonSphericalBase)

701

702# **) MIT License

703#

704# Copyright (C) 2016-2026 -- mrJean1 at Gmail -- All Rights Reserved.

705#

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

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

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

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

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

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

712#

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

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

715#

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

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

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

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

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

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

722# OTHER DEALINGS IN THE SOFTWARE.