Coverage for pygeodesy/nvectorBase.py: 96%

249 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2024-06-27 20:21 -0400

1 

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

3 

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

5L{LatLonNvectorBase} and L{NvectorBase} and function L{sumOf}. 

6 

7Pure Python implementation of C{n-vector}-based geodesy tools for ellipsoidal 

8earth models, transcoded from JavaScript originals by I{(C) Chris Veness 2005-2016} 

9and published under the same MIT Licence**, see U{Vector-based geodesy 

10<https://www.Movable-Type.co.UK/scripts/latlong-vectors.html>}. 

11''' 

12 

13# from pygeodesy.basics import map1 # from .namedTuples 

14from pygeodesy.constants import EPS, EPS1, EPS_2, R_M, _2_0, _N_2_0 

15# from pygeodesy.datums import _spherical_datum # from .formy 

16from pygeodesy.errors import IntersectionError, _ValueError, VectorError, \ 

17 _xattrs, _xkwds, _xkwds_pop2 

18from pygeodesy.fmath import fdot, fidw, hypot_ # PYCHOK fdot shared 

19from pygeodesy.fsums import Fsum, fsumf_ 

20from pygeodesy.formy import _isequalTo, n_xyz2latlon, n_xyz2philam, \ 

21 _spherical_datum 

22# from pygeodesy.internals import _under # from .named 

23from pygeodesy.interns import NN, _1_, _2_, _3_, _bearing_, _coincident_, \ 

24 _COMMASPACE_, _distance_, _h_, _insufficient_, \ 

25 _intersection_, _no_, _point_, _pole_, _SPACE_ 

26from pygeodesy.latlonBase import LatLonBase, _ALL_DOCS, _ALL_LAZY, _MODS 

27# from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS # from .latlonBase 

28from pygeodesy.named import _xother3, _under 

29from pygeodesy.namedTuples import Trilaterate5Tuple, Vector3Tuple, \ 

30 Vector4Tuple, map1 

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

32 property_RO, _update_all 

33from pygeodesy.streprs import Fmt, hstr, unstr 

34from pygeodesy.units import Bearing, Height, Radius_, Scalar 

35from pygeodesy.utily import sincos2d, _unrollon, _unrollon3 

36from pygeodesy.vector3d import Vector3d, _xyzhdlln4 

37 

38from math import fabs, sqrt 

39 

40__all__ = _ALL_LAZY.nvectorBase 

41__version__ = '24.06.12' 

42 

43 

44class NvectorBase(Vector3d): # XXX kept private 

45 '''Base class for ellipsoidal and spherical C{Nvector}s. 

46 ''' 

47 _datum = None # L{Datum}, overriden 

48 _h = Height(h=0) # height (C{meter}) 

49 _H = NN # height prefix (C{str}), '↑' in JS version 

50 

51 def __init__(self, x_xyz, y=None, z=None, h=0, datum=None, **ll_name): 

52 '''New n-vector normal to the earth's surface. 

53 

54 @arg x_xyz: X component of vector (C{scalar}) or (3-D) vector 

55 (C{Nvector}, L{Vector3d}, L{Vector3Tuple} or L{Vector4Tuple}). 

56 @kwarg y: Y component of vector (C{scalar}), required if B{C{x_xyz}} is 

57 C{scalar} and same units as B{C{x_xyz}}, ignored otherwise. 

58 @kwarg z: Z component of vector (C{scalar}), like B{C{y}}. 

59 @kwarg h: Optional height above surface (C{meter}). 

60 @kwarg datum: Optional, I{pass-thru} datum (L{Datum}). 

61 @kwarg ll_name: Optional C{B{name}=NN} (C{str}) and optional, original 

62 latlon C{B{ll}=None} (C{LatLon}). 

63 

64 @raise TypeError: Non-scalar B{C{x}}, B{C{y}} or B{C{z}} coordinate or 

65 B{C{x_xyz}} not an C{Nvector}, L{Vector3Tuple} or 

66 L{Vector4Tuple} or invalid B{C{datum}}. 

67 ''' 

68 h, d, ll, n = _xyzhdlln4(x_xyz, h, datum, **ll_name) 

69 Vector3d.__init__(self, x_xyz, y=y, z=z, ll=ll, name=n) 

70 if h: 

71 self.h = h 

72 if d is not None: 

73 self._datum = _spherical_datum(d, name=n) # pass-thru 

74 

75 @Property_RO 

76 def datum(self): 

77 '''Get the I{pass-thru} datum (C{Datum}) or C{None}. 

78 ''' 

79 return self._datum 

80 

81 @property_RO 

82 def Ecef(self): 

83 '''Get the ECEF I{class} (L{EcefKarney}), I{once}. 

84 ''' 

85 NvectorBase.Ecef = E = _MODS.ecef.EcefKarney # overwrite property_RO 

86 return E 

87 

88 @property_RO 

89 def ellipsoidalNvector(self): 

90 '''Get the C{Nvector type} iff ellipsoidal, overloaded in L{pygeodesy.ellipsoidalNvector.Nvector}. 

91 ''' 

92 return False 

93 

94 @property_doc_(''' the height above surface (C{meter}).''') 

95 def h(self): 

96 '''Get the height above surface (C{meter}). 

97 ''' 

98 return self._h 

99 

100 @h.setter # PYCHOK setter! 

101 def h(self, h): 

102 '''Set the height above surface (C{meter}). 

103 

104 @raise TypeError: If B{C{h}} invalid. 

105 

106 @raise VectorError: If B{C{h}} invalid. 

107 ''' 

108 h = Height(h=h, Error=VectorError) 

109 if self._h != h: 

110 _update_all(self) 

111 self._h = h 

112 

113 @property_doc_(''' the height prefix (C{str}).''') 

114 def H(self): 

115 '''Get the height prefix (C{str}). 

116 ''' 

117 return self._H 

118 

119 @H.setter # PYCHOK setter! 

120 def H(self, H): 

121 '''Set the height prefix (C{str}). 

122 ''' 

123 self._H = str(H) if H else NN 

124 

125 def hStr(self, prec=-2, m=NN): 

126 '''Return a string for the height B{C{h}}. 

127 

128 @kwarg prec: Number of (decimal) digits, unstripped (C{int}). 

129 @kwarg m: Optional unit of the height (C{str}). 

130 

131 @see: Function L{pygeodesy.hstr}. 

132 ''' 

133 return NN(self.H, hstr(self.h, prec=prec, m=m)) 

134 

135 @Property_RO 

136 def isEllipsoidal(self): 

137 '''Check whether this n-vector is ellipsoidal (C{bool} or C{None} if unknown). 

138 ''' 

139 return self.datum.isEllipsoidal if self.datum else None 

140 

141 @Property_RO 

142 def isSpherical(self): 

143 '''Check whether this n-vector is spherical (C{bool} or C{None} if unknown). 

144 ''' 

145 return self.datum.isSpherical if self.datum else None 

146 

147 @Property_RO 

148 def lam(self): 

149 '''Get the (geodetic) longitude in C{radians} (C{float}). 

150 ''' 

151 return self.philam.lam 

152 

153 @Property_RO 

154 def lat(self): 

155 '''Get the (geodetic) latitude in C{degrees} (C{float}). 

156 ''' 

157 return self.latlon.lat 

158 

159 @Property_RO 

160 def latlon(self): 

161 '''Get the (geodetic) lat-, longitude in C{degrees} (L{LatLon2Tuple}C{(lat, lon)}). 

162 ''' 

163 return n_xyz2latlon(self.x, self.y, self.z, name=self.name) 

164 

165 @Property_RO 

166 def latlonheight(self): 

167 '''Get the (geodetic) lat-, longitude in C{degrees} and height (L{LatLon3Tuple}C{(lat, lon, height)}). 

168 ''' 

169 return self.latlon.to3Tuple(self.h) 

170 

171 @Property_RO 

172 def latlonheightdatum(self): 

173 '''Get the lat-, longitude in C{degrees} with height and datum (L{LatLon4Tuple}C{(lat, lon, height, datum)}). 

174 ''' 

175 return self.latlonheight.to4Tuple(self.datum) 

176 

177 @Property_RO 

178 def lon(self): 

179 '''Get the (geodetic) longitude in C{degrees} (C{float}). 

180 ''' 

181 return self.latlon.lon 

182 

183 @Property_RO 

184 def phi(self): 

185 '''Get the (geodetic) latitude in C{radians} (C{float}). 

186 ''' 

187 return self.philam.phi 

188 

189 @Property_RO 

190 def philam(self): 

191 '''Get the (geodetic) lat-, longitude in C{radians} (L{PhiLam2Tuple}C{(phi, lam)}). 

192 ''' 

193 return n_xyz2philam(self.x, self.y, self.z, name=self.name) 

194 

195 @Property_RO 

196 def philamheight(self): 

197 '''Get the (geodetic) lat-, longitude in C{radians} and height (L{PhiLam3Tuple}C{(phi, lam, height)}). 

198 ''' 

199 return self.philam.to3Tuple(self.h) 

200 

201 @Property_RO 

202 def philamheightdatum(self): 

203 '''Get the lat-, longitude in C{radians} with height and datum (L{PhiLam4Tuple}C{(phi, lam, height, datum)}). 

204 ''' 

205 return self.philamheight.to4Tuple(self.datum) 

206 

207 @property_RO 

208 def sphericalNvector(self): 

209 '''Get the C{Nvector type} iff spherical, overloaded in L{pygeodesy.sphericalNvector.Nvector}. 

210 ''' 

211 return False 

212 

213 @deprecated_method 

214 def to2ab(self): # PYCHOK no cover 

215 '''DEPRECATED, use property L{philam}. 

216 

217 @return: A L{PhiLam2Tuple}C{(phi, lam)}. 

218 ''' 

219 return self.philam 

220 

221 @deprecated_method 

222 def to3abh(self, height=None): # PYCHOK no cover 

223 '''DEPRECATED, use property L{philamheight} or C{philam.to3Tuple(B{height})}. 

224 

225 @kwarg height: Optional height, overriding this 

226 n-vector's height (C{meter}). 

227 

228 @return: A L{PhiLam3Tuple}C{(phi, lam, height)}. 

229 

230 @raise ValueError: Invalid B{C{height}}. 

231 ''' 

232 return self.philamheight if height in (None, self.h) else \ 

233 self.philam.to3Tuple(height) 

234 

235 def toCartesian(self, h=None, Cartesian=None, datum=None, **Cartesian_kwds): 

236 '''Convert this n-vector to C{Nvector}-based cartesian (ECEF) coordinates. 

237 

238 @kwarg h: Optional height, overriding this n-vector's height (C{meter}). 

239 @kwarg Cartesian: Optional class to return the (ECEF) coordinates 

240 (C{Cartesian}). 

241 @kwarg datum: Optional datum (C{Datum}), overriding this datum. 

242 @kwarg Cartesian_kwds: Optional, additional B{C{Cartesian}} keyword 

243 arguments, ignored if C{B{Cartesian} is None}. 

244 

245 @return: The cartesian (ECEF) coordinates (B{C{Cartesian}}) or 

246 if C{B{Cartesian} is None}, an L{Ecef9Tuple}C{(x, y, z, 

247 lat, lon, height, C, M, datum)} with C{C} and C{M} if 

248 available. 

249 

250 @raise TypeError: Invalid B{C{Cartesian}} or B{C{Cartesian_kwds}} 

251 argument. 

252 

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

254 ''' 

255 D = _spherical_datum(datum or self.datum, name=self.name) 

256 E = D.ellipsoid 

257 h = self.h if h is None else Height(h) 

258 

259 x, y, z = self.x, self.y, self.z 

260 # Kenneth Gade eqn 22 

261 n = E.b / hypot_(x * E.a_b, y * E.a_b, z) 

262 r = h + n * E.a2_b2 

263 

264 x *= r 

265 y *= r 

266 z *= h + n 

267 

268 if Cartesian is None: 

269 r = self.Ecef(D).reverse(x, y, z, M=True) 

270 else: 

271 kwds = _xkwds(Cartesian_kwds, datum=D) # h=0 

272 r = Cartesian(x, y, z, **kwds) 

273 return self._xnamed(r) 

274 

275 @deprecated_method 

276 def to2ll(self): # PYCHOK no cover 

277 '''DEPRECATED, use property L{latlon}. 

278 

279 @return: A L{LatLon2Tuple}C{(lat, lon)}. 

280 ''' 

281 return self.latlon 

282 

283 @deprecated_method 

284 def to3llh(self, height=None): # PYCHOK no cover 

285 '''DEPRECATED, use property C{latlonheight} or C{latlon.to3Tuple(B{height})}. 

286 

287 @kwarg height: Optional height, overriding this 

288 n-vector's height (C{meter}). 

289 

290 @return: A L{LatLon3Tuple}C{(lat, lon, height)}. 

291 

292 @raise ValueError: Invalid B{C{height}}. 

293 ''' 

294 return self.latlonheight if height in (None, self.h) else \ 

295 self.latlon.to3Tuple(height) 

296 

297 def toLatLon(self, height=None, LatLon=None, datum=None, **LatLon_kwds): 

298 '''Convert this n-vector to an C{Nvector}-based geodetic point. 

299 

300 @kwarg height: Optional height, overriding this n-vector's 

301 height (C{meter}). 

302 @kwarg LatLon: Optional class to return the geodetic point 

303 (C{LatLon}) or C{None}. 

304 @kwarg datum: Optional, spherical datum (C{Datum}). 

305 @kwarg LatLon_kwds: Optional, additional B{C{LatLon}} keyword 

306 arguments, ignored if C{B{LatLon} is None}. 

307 

308 @return: The geodetic point (C{LatLon}) or if C{B{LatLon} is None}, 

309 an L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M, 

310 datum)} with C{C} and C{M} if available. 

311 

312 @raise TypeError: Invalid B{C{LatLon}} or B{C{LatLon_kwds}} 

313 argument. 

314 

315 @raise ValueError: Invalid B{C{height}}. 

316 ''' 

317 d = _spherical_datum(datum or self.datum, name=self.name) 

318 h = self.h if height is None else Height(height) 

319 # use self.Cartesian(Cartesian=None) for better accuracy of the height 

320 # than self.Ecef(d).forward(self.lat, self.lon, height=h, M=True) 

321 if LatLon is None: 

322 r = self.toCartesian(h=h, Cartesian=None, datum=d) 

323 else: 

324 kwds = _xkwds(LatLon_kwds, height=h, datum=d) 

325 r = LatLon(self.lat, self.lon, **self._name1__(kwds)) 

326 return r 

327 

328 def toStr(self, prec=5, fmt=Fmt.PAREN, sep=_COMMASPACE_): # PYCHOK expected 

329 '''Return a string representation of this n-vector. 

330 

331 Height component is only included if non-zero. 

332 

333 @kwarg prec: Number of (decimal) digits, unstripped (C{int}). 

334 @kwarg fmt: Enclosing backets format (C{str}). 

335 @kwarg sep: Optional separator between components (C{str}). 

336 

337 @return: Comma-separated C{"(x, y, z [, h])"} enclosed in 

338 B{C{fmt}} brackets (C{str}). 

339 ''' 

340 t = Vector3d.toStr(self, prec=prec, fmt=NN, sep=sep) 

341 if self.h: 

342 t = sep.join((t, self.hStr())) 

343 return (fmt % (t,)) if fmt else t 

344 

345 def toVector3d(self, norm=True): 

346 '''Convert this n-vector to a 3-D vector, I{ignoring height}. 

347 

348 @kwarg norm: If C{True}, normalize the 3-D vector (C{bool}). 

349 

350 @return: The (normalized) vector (L{Vector3d}). 

351 ''' 

352 v = Vector3d.unit(self) if norm else self 

353 return Vector3d(v.x, v.y, v.z, name=self.name) 

354 

355 @deprecated_method 

356 def to4xyzh(self, h=None): # PYCHOK no cover 

357 '''DEPRECATED, use property L{xyzh} or C{xyz.to4Tuple(B{h})}.''' 

358 return self.xyzh if h in (None, self.h) else Vector4Tuple( 

359 self.x, self.y, self.z, h, name=self.name) 

360 

361 def unit(self, ll=None): 

362 '''Normalize this n-vector to unit length. 

363 

364 @kwarg ll: Optional, original latlon (C{LatLon}). 

365 

366 @return: Normalized vector (C{Nvector}). 

367 ''' 

368 return _xattrs(Vector3d.unit(self, ll=ll), self, _under(_h_)) 

369 

370 @Property_RO 

371 def xyzh(self): 

372 '''Get this n-vector's components (L{Vector4Tuple}C{(x, y, z, h)}) 

373 ''' 

374 return self.xyz.to4Tuple(self.h) 

375 

376 

377NorthPole = NvectorBase(0, 0, +1, name='NorthPole') # North pole (C{Nvector}) 

378SouthPole = NvectorBase(0, 0, -1, name='SouthPole') # South pole (C{Nvector}) 

379 

380 

381class _N_vector_(NvectorBase): 

382 '''(INTERNAL) Minimal, low-overhead C{n-vector}. 

383 ''' 

384 def __init__(self, x, y, z, h=0, **name): 

385 self._x, self._y, self._z = x, y, z 

386 if h: 

387 self._h = h 

388 if name: 

389 self.name = name 

390 

391 

392class LatLonNvectorBase(LatLonBase): 

393 '''(INTERNAL) Base class for n-vector-based ellipsoidal and 

394 spherical C{LatLon} classes. 

395 ''' 

396 

397 def _update(self, updated, *attrs, **setters): # PYCHOK _Nv=None 

398 '''(INTERNAL) Zap cached attributes if updated. 

399 

400 @see: C{ellipsoidalNvector.LatLon} and C{sphericalNvector.LatLon} 

401 for the special case of B{C{_Nv}}. 

402 ''' 

403 if updated: 

404 _Nv, setters = _xkwds_pop2(setters, _Nv=None) 

405 if _Nv is not None: 

406 if _Nv._fromll is not None: 

407 _Nv._fromll = None 

408 self._Nv = None 

409 LatLonBase._update(self, updated, *attrs, **setters) 

410 

411# def distanceTo(self, other, **kwds): # PYCHOK no cover 

412# '''I{Must be overloaded}.''' 

413# self._notOverloaded(other, **kwds) 

414 

415 def intersections2(self, radius1, other, radius2, **kwds): # PYCHOK expected 

416 '''B{Not implemented}, throws a C{NotImplementedError} always.''' 

417 self._notImplemented(radius1, other, radius2, **kwds) 

418 

419 def others(self, *other, **name_other_up): 

420 '''Refined class comparison. 

421 

422 @arg other: The other instance (C{LatLonNvectorBase}). 

423 @kwarg name_other_up: Overriding C{name=other} and C{up=1} 

424 keyword arguments. 

425 

426 @return: The B{C{other}} if compatible. 

427 

428 @raise TypeError: Incompatible B{C{other}} C{type}. 

429 ''' 

430 if other: 

431 other0 = other[0] 

432 if isinstance(other0, (self.__class__, LatLonNvectorBase)): # XXX NvectorBase? 

433 return other0 

434 

435 other, name, up = _xother3(self, other, **name_other_up) 

436 if not isinstance(other, (self.__class__, LatLonNvectorBase)): # XXX NvectorBase? 

437 LatLonBase.others(self, other, name=name, up=up + 1) 

438 return other 

439 

440 def toNvector(self, **Nvector_and_kwds): # PYCHOK signature 

441 '''Convert this point to C{Nvector} components, I{including height}. 

442 

443 @kwarg Nvector_and_kwds: Optional C{Nvector} class and C{Nvector} keyword arguments, 

444 Specify C{B{Nvector}=...} to override this C{Nvector} class 

445 or use C{B{Nvector}=None}. 

446 

447 @return: An C{Nvector} or if C{Nvector is None}, a L{Vector4Tuple}C{(x, y, z, h)}. 

448 

449 @raise TypeError: Invalid C{Nvector} or other B{C{Nvector_and_kwds}} item. 

450 ''' 

451 return LatLonBase.toNvector(self, **_xkwds(Nvector_and_kwds, Nvector=NvectorBase)) 

452 

453 def triangulate(self, bearing1, other, bearing2, height=None, wrap=False): # PYCHOK signature 

454 '''Locate a point given this, an other point and the (initial) bearing 

455 from this and the other point. 

456 

457 @arg bearing1: Bearing at this point (compass C{degrees360}). 

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

459 @arg bearing2: Bearing at the other point (compass C{degrees360}). 

460 @kwarg height: Optional height at the triangulated point, overriding 

461 the mean height (C{meter}). 

462 @kwarg wrap: If C{True}, use this and the B{C{other}} point 

463 I{normalized} (C{bool}). 

464 

465 @return: Triangulated point (C{LatLon}). 

466 

467 @raise TypeError: Invalid B{C{other}} point. 

468 

469 @raise Valuerror: Points coincide. 

470 ''' 

471 return _triangulate(self, bearing1, self.others(other), bearing2, 

472 height=height, wrap=wrap, LatLon=self.classof) 

473 

474 def trilaterate(self, distance1, point2, distance2, point3, distance3, 

475 radius=R_M, height=None, useZ=False, wrap=False): 

476 '''Locate a point at given distances from this and two other points. 

477 

478 @arg distance1: Distance to this point (C{meter}, same units 

479 as B{C{radius}}). 

480 @arg point2: Second reference point (C{LatLon}). 

481 @arg distance2: Distance to point2 (C{meter}, same units as 

482 B{C{radius}}). 

483 @arg point3: Third reference point (C{LatLon}). 

484 @arg distance3: Distance to point3 (C{meter}, same units as 

485 B{C{radius}}). 

486 @kwarg radius: Mean earth radius (C{meter}). 

487 @kwarg height: Optional height at trilaterated point, overriding 

488 the mean height (C{meter}, same units as B{C{radius}}). 

489 @kwarg useZ: Include Z component iff non-NaN, non-zero (C{bool}). 

490 @kwarg wrap: If C{True}, use this, B{C{point2}} and B{C{point3}} 

491 I{normalized} (C{bool}). 

492 

493 @return: Trilaterated point (C{LatLon}). 

494 

495 @raise IntersectionError: No intersection, trilateration failed. 

496 

497 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}. 

498 

499 @raise ValueError: Some B{C{points}} coincide or invalid B{C{distance1}}, 

500 B{C{distance2}}, B{C{distance3}} or B{C{radius}}. 

501 

502 @see: U{Trilateration<https://WikiPedia.org/wiki/Trilateration>}, 

503 Veness' JavaScript U{Trilateration<https://www.Movable-Type.co.UK/ 

504 scripts/latlong-vectors.html>} and method C{LatLon.trilaterate5} 

505 of other, non-C{Nvector LatLon} classes. 

506 ''' 

507 return _trilaterate(self, distance1, self.others(point2=point2), distance2, 

508 self.others(point3=point3), distance3, 

509 radius=radius, height=height, useZ=useZ, 

510 wrap=wrap, LatLon=self.classof) 

511 

512 def trilaterate5(self, distance1, point2, distance2, point3, distance3, # PYCHOK signature 

513 area=False, eps=EPS1, radius=R_M, wrap=False): 

514 '''B{Not implemented} for C{B{area}=True} and falls back to method 

515 C{trilaterate} otherwise. 

516 

517 @return: A L{Trilaterate5Tuple}C{(min, minPoint, max, maxPoint, n)} 

518 with a single trilaterated intersection C{minPoint I{is} 

519 maxPoint}, C{min I{is} max} the nearest intersection 

520 margin and count C{n = 1}. 

521 

522 @raise NotImplementedError: Keyword argument C{B{area}=True} not 

523 (yet) supported. 

524 

525 @see: Method L{trilaterate} for other and more details. 

526 ''' 

527 if area: 

528 self._notImplemented(area=area) 

529 

530 t = _trilaterate(self, distance1, self.others(point2=point2), distance2, 

531 self.others(point3=point3), distance3, 

532 radius=radius, useZ=True, wrap=wrap, 

533 LatLon=self.classof) 

534 # ... and handle B{C{eps}} and C{IntersectionError} 

535 # like function C{.latlonBase._trilaterate5} 

536 d = self.distanceTo(t, radius=radius, wrap=wrap) # PYCHOK distanceTo 

537 d = min(fabs(distance1 - d), fabs(distance2 - d), fabs(distance3 - d)) 

538 if d < eps: # min is max, minPoint is maxPoint 

539 return Trilaterate5Tuple(d, t, d, t, 1) # n = 1 

540 t = _SPACE_(_no_(_intersection_), Fmt.PAREN(min.__name__, Fmt.f(d, prec=3))) 

541 raise IntersectionError(area=area, eps=eps, radius=radius, wrap=wrap, txt=t) 

542 

543 

544def _nsumOf(nvs, h_None, Vector, Vector_kwds): # .sphericalNvector, .vector3d 

545 '''(INTERNAL) Separated to allow callers to embellish exceptions. 

546 ''' 

547 X, Y, Z, n = Fsum(), Fsum(), Fsum(), 0 

548 H = Fsum() if h_None is None else n 

549 for n, v in enumerate(nvs or ()): # one pass 

550 X += v.x 

551 Y += v.y 

552 Z += v.z 

553 H += v.h 

554 if n < 1: 

555 raise ValueError(_SPACE_(Fmt.PARENSPACED(len=n), _insufficient_)) 

556 

557 x, y, z = map1(float, X, Y, Z) 

558 h = H.fover(n) if h_None is None else h_None 

559 return Vector3Tuple(x, y, z).to4Tuple(h) if Vector is None else \ 

560 Vector(x, y, z, **_xkwds(Vector_kwds, h=h)) 

561 

562 

563def sumOf(nvectors, Vector=None, h=None, **Vector_kwds): 

564 '''Return the I{vectorial} sum of two or more n-vectors. 

565 

566 @arg nvectors: Vectors to be added (C{Nvector}[]). 

567 @kwarg Vector: Optional class for the vectorial sum (C{Nvector}) 

568 or C{None}. 

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

570 @kwarg Vector_kwds: Optional, additional B{C{Vector}} keyword 

571 arguments, ignored if C{B{Vector} is None}. 

572 

573 @return: Vectorial sum (B{C{Vector}}) or a L{Vector4Tuple}C{(x, y, 

574 z, h)} if C{B{Vector} is None}. 

575 

576 @raise VectorError: No B{C{nvectors}}. 

577 ''' 

578 try: 

579 return _nsumOf(nvectors, h, Vector, Vector_kwds) 

580 except (TypeError, ValueError) as x: 

581 raise VectorError(nvectors=nvectors, Vector=Vector, cause=x) 

582 

583 

584def _triangulate(point1, bearing1, point2, bearing2, height=None, 

585 wrap=False, **LatLon_and_kwds): 

586 # (INTERNAL) Locate a point given two known points and initial 

587 # bearings from those points, see C{LatLon.triangulate} above 

588 

589 def _gc(p, b, _i_): 

590 n = p.toNvector() 

591 de = NorthPole.cross(n, raiser=_pole_).unit() # east vector @ n 

592 dn = n.cross(de) # north vector @ n 

593 s, c = sincos2d(Bearing(b, name=_bearing_ + _i_)) 

594 dest = de.times(s) 

595 dnct = dn.times(c) 

596 d = dnct.plus(dest) # direction vector @ n 

597 return n.cross(d) # great circle point + bearing 

598 

599 if wrap: 

600 point2 = _unrollon(point1, point2, wrap=wrap) 

601 if _isequalTo(point1, point2, eps=EPS): 

602 raise _ValueError(points=point2, wrap=wrap, txt=_coincident_) 

603 

604 gc1 = _gc(point1, bearing1, _1_) # great circle p1 + b1 

605 gc2 = _gc(point2, bearing2, _2_) # great circle p2 + b2 

606 

607 n = gc1.cross(gc2, raiser=_point_) # n-vector of intersection point 

608 h = point1._havg(point2, h=height) 

609 kwds = _xkwds(LatLon_and_kwds, height=h) 

610 return n.toLatLon(**kwds) # Nvector(n.x, n.y, n.z).toLatLon(...) 

611 

612 

613def _trilaterate(point1, distance1, point2, distance2, point3, distance3, 

614 radius=R_M, height=None, useZ=False, 

615 wrap=False, **LatLon_and_kwds): 

616 # (INTERNAL) Locate a point at given distances from 

617 # three other points, see LatLon.triangulate above 

618 

619 def _nr2(p, d, r, _i_, *qs): # .toNvector and angular distance squared 

620 for q in qs: 

621 if _isequalTo(p, q, eps=EPS): 

622 raise _ValueError(points=p, txt=_coincident_) 

623 return p.toNvector(), (Scalar(d, name=_distance_ + _i_) / r)**2 

624 

625 p1, r = point1, Radius_(radius) 

626 p2, p3, _ = _unrollon3(p1, point2, point3, wrap) 

627 

628 n1, r12 = _nr2(p1, distance1, r, _1_) 

629 n2, r22 = _nr2(p2, distance2, r, _2_, p1) 

630 n3, r32 = _nr2(p3, distance3, r, _3_, p1, p2) 

631 

632 # the following uses x,y coordinate system with origin at n1, x axis n1->n2 

633 y = n3.minus(n1) 

634 x = n2.minus(n1) 

635 z = None 

636 

637 d = x.length # distance n1->n2 

638 if d > EPS_2: # and y.length > EPS_2: 

639 X = x.unit() # unit vector in x direction n1->n2 

640 i = X.dot(y) # signed magnitude of x component of n1->n3 

641 Y = y.minus(X.times(i)).unit() # unit vector in y direction 

642 j = Y.dot(y) # signed magnitude of y component of n1->n3 

643 if fabs(j) > EPS_2: 

644 # courtesy of U{Carlos Freitas<https://GitHub.com/mrJean1/PyGeodesy/issues/33>} 

645 x = fsumf_(r12, -r22, d**2) / (d * _2_0) # n1->intersection x- and ... 

646 y = fsumf_(r12, -r32, i**2, j**2, x * i * _N_2_0) / (j * _2_0) # ... y-component 

647 # courtesy of U{AleixDev<https://GitHub.com/mrJean1/PyGeodesy/issues/43>} 

648 z = fsumf_(max(r12, r22, r32), -(x**2), -(y**2)) # XXX not just r12! 

649 if z > EPS: 

650 n = n1.plus(X.times(x)).plus(Y.times(y)) 

651 if useZ: # include Z component 

652 Z = X.cross(Y) # unit vector perpendicular to plane 

653 n = n.plus(Z.times(sqrt(z))) 

654 if height is None: 

655 h = fidw((point1.height, point2.height, point3.height), 

656 map1(fabs, distance1, distance2, distance3)) 

657 else: 

658 h = Height(height) 

659 kwds = _xkwds(LatLon_and_kwds, height=h) 

660 return n.toLatLon(**kwds) # Nvector(n.x, n.y, n.z).toLatLon(...) 

661 

662 # no intersection, d < EPS_2 or fabs(j) < EPS_2 or z < EPS 

663 t = _SPACE_(_no_, _intersection_, NN) 

664 raise IntersectionError(point1=point1, distance1=distance1, 

665 point2=point2, distance2=distance2, 

666 point3=point3, distance3=distance3, 

667 txt=unstr(t, z=z, useZ=useZ, wrap=wrap)) 

668 

669 

670__all__ += _ALL_DOCS(LatLonNvectorBase, NvectorBase, sumOf) # classes 

671 

672# **) MIT License 

673# 

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

675# 

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

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

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

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

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

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

682# 

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

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

685# 

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

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

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

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

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

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

692# OTHER DEALINGS IN THE SOFTWARE.