Coverage for pygeodesy/nvectorBase.py: 96%
242 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-10-11 16:04 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2023-10-11 16:04 -0400
2# -*- coding: utf-8 -*-
4u'''(INTERNAL) Private elliposiodal and spherical C{Nvector} base classes
5L{LatLonNvectorBase} and L{NvectorBase} and function L{sumOf}.
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'''
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 _xkwds, _xkwds_pop
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
22from pygeodesy.interns import NN, _1_, _2_, _3_, _bearing_, _coincident_, \
23 _COMMASPACE_, _distance_, _h_, _insufficient_, \
24 _intersection_, _no_, _NorthPole_, _point_, \
25 _pole_, _SPACE_, _SouthPole_, _under
26from pygeodesy.latlonBase import LatLonBase, _ALL_DOCS, _MODS
27# from pygeodesy.lazily import _ALL_DOCS, _ALL_MODS as _MODS # from .latlonBase
28from pygeodesy.named import notImplemented, _xother3
29from pygeodesy.namedTuples import Trilaterate5Tuple, Vector3Tuple, \
30 Vector4Tuple, map1
31from pygeodesy.props import deprecated_method, property_doc_, \
32 Property_RO, _update_all
33from pygeodesy.streprs import Fmt, hstr, unstr, _xattrs
34from pygeodesy.units import Bearing, Height, Radius_, Scalar
35from pygeodesy.utily import sincos2d, _unrollon, _unrollon3
36from pygeodesy.vector3d import Vector3d, _xyzhdn3
38from math import fabs, sqrt
40__all__ = (_NorthPole_, _SouthPole_) # constants
41__version__ = '23.09.22'
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
51 def __init__(self, x_xyz, y=None, z=None, h=0, ll=None, datum=None, name=NN):
52 '''New n-vector normal to the earth's surface.
54 @arg x_xyz: X component of vector (C{scalar}) or (3-D) vector
55 (C{Nvector}, L{Vector3d}, L{Vector3Tuple} or
56 L{Vector4Tuple}).
57 @kwarg y: Y component of vector (C{scalar}), ignored if B{C{x_xyz}}
58 is not C{scalar}, otherwise same units as B{C{x_xyz}}.
59 @kwarg z: Z component of vector (C{scalar}), ignored if B{C{x_xyz}}
60 is not C{scalar}, otherwise same units as B{C{x_xyz}}.
61 @kwarg h: Optional height above surface (C{meter}).
62 @kwarg ll: Optional, original latlon (C{LatLon}).
63 @kwarg datum: Optional, I{pass-thru} datum (L{Datum}).
64 @kwarg name: Optional name (C{str}).
66 @raise TypeError: Non-scalar B{C{x}}, B{C{y}} or B{C{z}}
67 coordinate or B{C{x}} not an C{Nvector},
68 L{Vector3Tuple} or L{Vector4Tuple} or
69 invalid B{C{datum}}.
71 @example:
73 >>> from pygeodesy.sphericalNvector import Nvector
74 >>> v = Nvector(0.5, 0.5, 0.7071, 1)
75 >>> v.toLatLon() # 45.0°N, 045.0°E, +1.00m
76 '''
77 h, d, n = _xyzhdn3(x_xyz, h, datum, ll)
78 Vector3d.__init__(self, x_xyz, y=y, z=z, ll=ll, name=name or n)
79 if h:
80 self.h = h
81 if d is not None:
82 self._datum = _spherical_datum(d, name=self.name) # pass-thru
84 @Property_RO
85 def datum(self):
86 '''Get the I{pass-thru} datum (C{Datum}) or C{None}.
87 '''
88 return self._datum
90 @Property_RO
91 def Ecef(self):
92 '''Get the ECEF I{class} (L{EcefKarney}), I{lazily}.
93 '''
94 return _MODS.ecef.EcefKarney # default
96 @property_doc_(''' the height above surface (C{meter}).''')
97 def h(self):
98 '''Get the height above surface (C{meter}).
99 '''
100 return self._h
102 @h.setter # PYCHOK setter!
103 def h(self, h):
104 '''Set the height above surface (C{meter}).
106 @raise TypeError: If B{C{h}} invalid.
108 @raise VectorError: If B{C{h}} invalid.
109 '''
110 h = Height(h=h, Error=VectorError)
111 if self._h != h:
112 _update_all(self)
113 self._h = h
115 @property_doc_(''' the height prefix (C{str}).''')
116 def H(self):
117 '''Get the height prefix (C{str}).
118 '''
119 return self._H
121 @H.setter # PYCHOK setter!
122 def H(self, H):
123 '''Set the height prefix (C{str}).
124 '''
125 self._H = str(H) if H else NN
127 def hStr(self, prec=-2, m=NN):
128 '''Return a string for the height B{C{h}}.
130 @kwarg prec: Number of (decimal) digits, unstripped (C{int}).
131 @kwarg m: Optional unit of the height (C{str}).
133 @see: Function L{pygeodesy.hstr}.
134 '''
135 return NN(self.H, hstr(self.h, prec=prec, m=m))
137 @Property_RO
138 def isEllipsoidal(self):
139 '''Check whether this n-vector is ellipsoidal (C{bool} or C{None} if unknown).
140 '''
141 return self.datum.isEllipsoidal if self.datum else None
143 @Property_RO
144 def isSpherical(self):
145 '''Check whether this n-vector is spherical (C{bool} or C{None} if unknown).
146 '''
147 return self.datum.isSpherical if self.datum else None
149 @Property_RO
150 def lam(self):
151 '''Get the (geodetic) longitude in C{radians} (C{float}).
152 '''
153 return self.philam.lam
155 @Property_RO
156 def lat(self):
157 '''Get the (geodetic) latitude in C{degrees} (C{float}).
158 '''
159 return self.latlon.lat
161 @Property_RO
162 def latlon(self):
163 '''Get the (geodetic) lat-, longitude in C{degrees} (L{LatLon2Tuple}C{(lat, lon)}).
164 '''
165 return n_xyz2latlon(self.x, self.y, self.z, name=self.name)
167 @Property_RO
168 def latlonheight(self):
169 '''Get the (geodetic) lat-, longitude in C{degrees} and height (L{LatLon3Tuple}C{(lat, lon, height)}).
170 '''
171 return self.latlon.to3Tuple(self.h)
173 @Property_RO
174 def latlonheightdatum(self):
175 '''Get the lat-, longitude in C{degrees} with height and datum (L{LatLon4Tuple}C{(lat, lon, height, datum)}).
176 '''
177 return self.latlonheight.to4Tuple(self.datum)
179 @Property_RO
180 def lon(self):
181 '''Get the (geodetic) longitude in C{degrees} (C{float}).
182 '''
183 return self.latlon.lon
185 @Property_RO
186 def phi(self):
187 '''Get the (geodetic) latitude in C{radians} (C{float}).
188 '''
189 return self.philam.phi
191 @Property_RO
192 def philam(self):
193 '''Get the (geodetic) lat-, longitude in C{radians} (L{PhiLam2Tuple}C{(phi, lam)}).
194 '''
195 return n_xyz2philam(self.x, self.y, self.z, name=self.name)
197 @Property_RO
198 def philamheight(self):
199 '''Get the (geodetic) lat-, longitude in C{radians} and height (L{PhiLam3Tuple}C{(phi, lam, height)}).
200 '''
201 return self.philam.to3Tuple(self.h)
203 @Property_RO
204 def philamheightdatum(self):
205 '''Get the lat-, longitude in C{radians} with height and datum (L{PhiLam4Tuple}C{(phi, lam, height, datum)}).
206 '''
207 return self.philamheight.to4Tuple(self.datum)
209 @deprecated_method
210 def to2ab(self): # PYCHOK no cover
211 '''DEPRECATED, use property L{philam}.
213 @return: A L{PhiLam2Tuple}C{(phi, lam)}.
214 '''
215 return self.philam
217 @deprecated_method
218 def to3abh(self, height=None): # PYCHOK no cover
219 '''DEPRECATED, use property L{philamheight} or C{philam.to3Tuple(B{height})}.
221 @kwarg height: Optional height, overriding this
222 n-vector's height (C{meter}).
224 @return: A L{PhiLam3Tuple}C{(phi, lam, height)}.
226 @raise ValueError: Invalid B{C{height}}.
227 '''
228 return self.philamheight if height in (None, self.h) else \
229 self.philam.to3Tuple(height)
231 def toCartesian(self, h=None, Cartesian=None, datum=None, **Cartesian_kwds):
232 '''Convert this n-vector to C{Nvector}-based cartesian (ECEF) coordinates.
234 @kwarg h: Optional height, overriding this n-vector's height (C{meter}).
235 @kwarg Cartesian: Optional class to return the (ECEF) coordinates
236 (C{Cartesian}).
237 @kwarg datum: Optional datum (C{Datum}), overriding this datum.
238 @kwarg Cartesian_kwds: Optional, additional B{C{Cartesian}} keyword
239 arguments, ignored if C{B{Cartesian} is None}.
241 @return: The cartesian (ECEF) coordinates (B{C{Cartesian}}) or
242 if C{B{Cartesian} is None}, an L{Ecef9Tuple}C{(x, y, z,
243 lat, lon, height, C, M, datum)} with C{C} and C{M} if
244 available.
246 @raise TypeError: Invalid B{C{Cartesian}} or B{C{Cartesian_kwds}}
247 argument.
249 @raise ValueError: Invalid B{C{h}}.
251 @example:
253 >>> v = Nvector(0.5, 0.5, 0.7071)
254 >>> c = v.toCartesian() # [3194434, 3194434, 4487327]
255 >>> p = c.toLatLon() # 45.0°N, 45.0°E
256 '''
257 d = _spherical_datum(datum or self.datum, name=self.name)
258 E = d.ellipsoid
259 h = self.h if h is None else Height(h)
261 x, y, z = self.x, self.y, self.z
262 # Kenneth Gade eqn 22
263 n = E.b / hypot_(x * E.a_b, y * E.a_b, z)
264 r = h + n * E.a2_b2
266 x *= r
267 y *= r
268 z *= h + n
270 if Cartesian is None:
271 r = self.Ecef(d).reverse(x, y, z, M=True)
272 else:
273 kwds = _xkwds(Cartesian_kwds, datum=d) # h=0
274 r = Cartesian(x, y, z, **kwds)
275 return self._xnamed(r)
277 @deprecated_method
278 def to2ll(self): # PYCHOK no cover
279 '''DEPRECATED, use property L{latlon}.
281 @return: A L{LatLon2Tuple}C{(lat, lon)}.
282 '''
283 return self.latlon
285 @deprecated_method
286 def to3llh(self, height=None): # PYCHOK no cover
287 '''DEPRECATED, use property C{latlonheight} or C{latlon.to3Tuple(B{height})}.
289 @kwarg height: Optional height, overriding this
290 n-vector's height (C{meter}).
292 @return: A L{LatLon3Tuple}C{(lat, lon, height)}.
294 @raise ValueError: Invalid B{C{height}}.
295 '''
296 return self.latlonheight if height in (None, self.h) else \
297 self.latlon.to3Tuple(height)
299 def toLatLon(self, height=None, LatLon=None, datum=None, **LatLon_kwds):
300 '''Convert this n-vector to an C{Nvector}-based geodetic point.
302 @kwarg height: Optional height, overriding this n-vector's
303 height (C{meter}).
304 @kwarg LatLon: Optional class to return the geodetic point
305 (C{LatLon}) or C{None}.
306 @kwarg datum: Optional, spherical datum (C{Datum}).
307 @kwarg LatLon_kwds: Optional, additional B{C{LatLon}} keyword
308 arguments, ignored if C{B{LatLon} is None}.
310 @return: The geodetic point (C{LatLon}) or if C{B{LatLon} is None},
311 an L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M,
312 datum)} with C{C} and C{M} if available.
314 @raise TypeError: Invalid B{C{LatLon}} or B{C{LatLon_kwds}}
315 argument.
317 @raise ValueError: Invalid B{C{height}}.
319 @example:
321 >>> v = Nvector(0.5, 0.5, 0.7071)
322 >>> p = v.toLatLon() # 45.0°N, 45.0°E
323 '''
324 d = _spherical_datum(datum or self.datum, name=self.name)
325 h = self.h if height is None else Height(height)
326 # use self.Cartesian(Cartesian=None) for better accuracy of the height
327 # than self.Ecef(d).forward(self.lat, self.lon, height=h, M=True)
328 if LatLon is None:
329 r = self.toCartesian(h=h, Cartesian=None, datum=d)
330 else:
331 kwds = _xkwds(LatLon_kwds, height=h, datum=d)
332 r = self._xnamed(LatLon(self.lat, self.lon, **kwds))
333 return r
335 def toStr(self, prec=5, fmt=Fmt.PAREN, sep=_COMMASPACE_): # PYCHOK expected
336 '''Return a string representation of this n-vector.
338 Height component is only included if non-zero.
340 @kwarg prec: Number of (decimal) digits, unstripped (C{int}).
341 @kwarg fmt: Enclosing backets format (C{str}).
342 @kwarg sep: Optional separator between components (C{str}).
344 @return: Comma-separated C{"(x, y, z [, h])"} enclosed in
345 B{C{fmt}} brackets (C{str}).
347 @example:
349 >>> Nvector(0.5, 0.5, 0.7071).toStr() # (0.5, 0.5, 0.7071)
350 >>> Nvector(0.5, 0.5, 0.7071, 1).toStr(-3) # (0.500, 0.500, 0.707, +1.00)
351 '''
352 t = Vector3d.toStr(self, prec=prec, fmt=NN, sep=sep)
353 if self.h:
354 t = sep.join((t, self.hStr()))
355 return (fmt % (t,)) if fmt else t
357 def toVector3d(self, norm=True):
358 '''Convert this n-vector to a 3-D vector, I{ignoring
359 the height}.
361 @kwarg norm: Normalize the 3-D vector (C{bool}).
363 @return: The (normalized) vector (L{Vector3d}).
364 '''
365 v = Vector3d.unit(self) if norm else self
366 return Vector3d(v.x, v.y, v.z, name=self.name)
368 @deprecated_method
369 def to4xyzh(self, h=None): # PYCHOK no cover
370 '''DEPRECATED, use property L{xyzh} or C{xyz.to4Tuple(B{h})}.
371 '''
372 return self.xyzh if h in (None, self.h) else Vector4Tuple(
373 self.x, self.y, self.z, h, name=self.name)
375 def unit(self, ll=None):
376 '''Normalize this n-vector to unit length.
378 @kwarg ll: Optional, original latlon (C{LatLon}).
380 @return: Normalized vector (C{Nvector}).
381 '''
382 return _xattrs(Vector3d.unit(self, ll=ll), _under(_h_))
384 @Property_RO
385 def xyzh(self):
386 '''Get this n-vector's components (L{Vector4Tuple}C{(x, y, z, h)})
387 '''
388 return self.xyz.to4Tuple(self.h)
391NorthPole = NvectorBase(0, 0, +1, name=_NorthPole_) # North pole (C{Nvector})
392SouthPole = NvectorBase(0, 0, -1, name=_SouthPole_) # South pole (C{Nvector})
395class _N_vector_(NvectorBase):
396 '''(INTERNAL) Minimal, low-overhead C{n-vector}.
397 '''
398 def __init__(self, x, y, z, h=0, name=NN):
399 self._x, self._y, self._z = x, y, z
400 if h:
401 self._h = h
402 if name:
403 self.name = name
406class LatLonNvectorBase(LatLonBase):
407 '''(INTERNAL) Base class for n-vector-based ellipsoidal
408 and spherical C{LatLon} classes.
409 '''
411 def _update(self, updated, *attrs, **setters): # PYCHOK _Nv=None
412 '''(INTERNAL) Zap cached attributes if updated.
414 @see: C{ellipsoidalNvector.LatLon} and C{sphericalNvector.LatLon}
415 for the special case of B{C{_Nv}}.
416 '''
417 if updated:
418 _Nv = _xkwds_pop(setters, _Nv=None)
419 if _Nv is not None:
420 if _Nv._fromll is not None:
421 _Nv._fromll = None
422 self._Nv = None
423 LatLonBase._update(self, updated, *attrs, **setters)
425# def distanceTo(self, other, **kwds): # PYCHOK no cover
426# '''I{Must be overloaded}.'''
427# _MODS.named.notOverloaded(self, other, **kwds)
429 def intersections2(self, radius1, other, radius2, **kwds): # PYCHOK expected
430 '''B{Not implemented}, throws a C{NotImplementedError} always.
431 '''
432 notImplemented(self, radius1, other, radius2, **kwds)
434 def others(self, *other, **name_other_up):
435 '''Refined class comparison.
437 @arg other: The other instance (C{LatLonNvectorBase}).
438 @kwarg name_other_up: Overriding C{name=other} and C{up=1}
439 keyword arguments.
441 @return: The B{C{other}} if compatible.
443 @raise TypeError: Incompatible B{C{other}} C{type}.
444 '''
445 if other:
446 other0 = other[0]
447 if isinstance(other0, (self.__class__, LatLonNvectorBase)): # XXX NvectorBase?
448 return other0
450 other, name, up = _xother3(self, other, **name_other_up)
451 if not isinstance(other, (self.__class__, LatLonNvectorBase)): # XXX NvectorBase?
452 LatLonBase.others(self, other, name=name, up=up + 1)
453 return other
455 def toNvector(self, Nvector=NvectorBase, **Nvector_kwds): # PYCHOK signature
456 '''Convert this point to C{Nvector} components, I{including height}.
458 @kwarg Nvector_kwds: Optional, additional B{C{Nvector}} keyword
459 arguments, ignored if C{B{Nvector} is None}.
461 @return: An B{C{Nvector}} or a L{Vector4Tuple}C{(x, y, z, h)} if
462 B{C{Nvector}} is C{None}.
464 @raise TypeError: Invalid B{C{Nvector}} or B{C{Nvector_kwds}}
465 argument.
466 '''
467 return LatLonBase.toNvector(self, Nvector=Nvector, **Nvector_kwds)
469 def triangulate(self, bearing1, other, bearing2, height=None, wrap=False):
470 '''Locate a point given this and an other point and a bearing
471 at this and the other point.
473 @arg bearing1: Bearing at this point (compass C{degrees360}).
474 @arg other: The other point (C{LatLon}).
475 @arg bearing2: Bearing at the other point (compass C{degrees360}).
476 @kwarg height: Optional height at the triangulated point,
477 overriding the mean height (C{meter}).
478 @kwarg wrap: If C{True}, use this and the B{C{other}} point
479 I{normalized} (C{bool}).
481 @return: Triangulated point (C{LatLon}).
483 @raise TypeError: Invalid B{C{other}} point.
485 @raise Valuerror: Points coincide.
487 @example:
489 >>> p = LatLon("47°18.228'N","002°34.326'W") # Basse Castouillet
490 >>> q = LatLon("47°18.664'N","002°31.717'W") # Basse Hergo
491 >>> t = p.triangulate(7, q, 295) # 47.323667°N, 002.568501°W'
492 '''
493 return _triangulate(self, bearing1, self.others(other), bearing2,
494 height=height, wrap=wrap, LatLon=self.classof)
496 def trilaterate(self, distance1, point2, distance2, point3, distance3,
497 radius=R_M, height=None, useZ=False, wrap=False):
498 '''Locate a point at given distances from this and two other points.
500 @arg distance1: Distance to this point (C{meter}, same units
501 as B{C{radius}}).
502 @arg point2: Second reference point (C{LatLon}).
503 @arg distance2: Distance to point2 (C{meter}, same units as
504 B{C{radius}}).
505 @arg point3: Third reference point (C{LatLon}).
506 @arg distance3: Distance to point3 (C{meter}, same units as
507 B{C{radius}}).
508 @kwarg radius: Mean earth radius (C{meter}).
509 @kwarg height: Optional height at trilaterated point, overriding
510 the mean height (C{meter}, same units as B{C{radius}}).
511 @kwarg useZ: Include Z component iff non-NaN, non-zero (C{bool}).
512 @kwarg wrap: If C{True}, use this, B{C{point2}} and B{C{point3}}
513 I{normalized} (C{bool}).
515 @return: Trilaterated point (C{LatLon}).
517 @raise IntersectionError: No intersection, trilateration failed.
519 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}.
521 @raise ValueError: Some B{C{points}} coincide or invalid B{C{distance1}},
522 B{C{distance2}}, B{C{distance3}} or B{C{radius}}.
524 @see: U{Trilateration<https://WikiPedia.org/wiki/Trilateration>},
525 Veness' JavaScript U{Trilateration<https://www.Movable-Type.co.UK/
526 scripts/latlong-vectors.html>} and method C{LatLon.trilaterate5}
527 of other, non-C{Nvector LatLon} classes.
528 '''
529 return _trilaterate(self, distance1, self.others(point2=point2), distance2,
530 self.others(point3=point3), distance3,
531 radius=radius, height=height, useZ=useZ,
532 wrap=wrap, LatLon=self.classof)
534 def trilaterate5(self, distance1, point2, distance2, point3, distance3, # PYCHOK signature
535 area=False, eps=EPS1, radius=R_M, wrap=False):
536 '''B{Not implemented} for C{B{area}=True} and falls back to method
537 C{trilaterate} otherwise.
539 @return: A L{Trilaterate5Tuple}C{(min, minPoint, max, maxPoint, n)}
540 with a single trilaterated intersection C{minPoint I{is}
541 maxPoint}, C{min I{is} max} the nearest intersection
542 margin and count C{n = 1}.
544 @raise NotImplementedError: Keyword argument C{B{area}=True} not
545 (yet) supported.
547 @see: Method L{trilaterate} for other and more details.
548 '''
549 if area:
550 notImplemented(self, area=area)
552 t = _trilaterate(self, distance1, self.others(point2=point2), distance2,
553 self.others(point3=point3), distance3,
554 radius=radius, useZ=True, wrap=wrap,
555 LatLon=self.classof)
556 # ... and handle B{C{eps}} and C{IntersectionError}
557 # like function C{.latlonBase._trilaterate5}
558 d = self.distanceTo(t, radius=radius, wrap=wrap) # PYCHOK distanceTo
559 d = min(fabs(distance1 - d), fabs(distance2 - d), fabs(distance3 - d))
560 if d < eps: # min is max, minPoint is maxPoint
561 return Trilaterate5Tuple(d, t, d, t, 1) # n = 1
562 t = _SPACE_(_no_(_intersection_), Fmt.PAREN(min.__name__, Fmt.f(d, prec=3)))
563 raise IntersectionError(area=area, eps=eps, radius=radius, wrap=wrap, txt=t)
566def _nsumOf(nvs, h_None, Vector, Vector_kwds): # .sphericalNvector, .vector3d
567 '''(INTERNAL) Separated to allow callers to embellish exceptions.
568 '''
569 X, Y, Z, n = Fsum(), Fsum(), Fsum(), 0
570 H = Fsum() if h_None is None else n
571 for n, v in enumerate(nvs or ()): # one pass
572 X += v.x
573 Y += v.y
574 Z += v.z
575 H += v.h
576 if n < 1:
577 raise ValueError(_SPACE_(Fmt.PARENSPACED(len=n), _insufficient_))
579 x, y, z = map1(float, X, Y, Z)
580 h = H.fover(n) if h_None is None else h_None
581 return Vector3Tuple(x, y, z).to4Tuple(h) if Vector is None else \
582 Vector(x, y, z, **_xkwds(Vector_kwds, h=h))
585def sumOf(nvectors, Vector=None, h=None, **Vector_kwds):
586 '''Return the I{vectorial} sum of two or more n-vectors.
588 @arg nvectors: Vectors to be added (C{Nvector}[]).
589 @kwarg Vector: Optional class for the vectorial sum (C{Nvector})
590 or C{None}.
591 @kwarg h: Optional height, overriding the mean height (C{meter}).
592 @kwarg Vector_kwds: Optional, additional B{C{Vector}} keyword
593 arguments, ignored if C{B{Vector} is None}.
595 @return: Vectorial sum (B{C{Vector}}) or a L{Vector4Tuple}C{(x, y,
596 z, h)} if B{C{Vector}} is C{None}.
598 @raise VectorError: No B{C{nvectors}}.
599 '''
600 try:
601 return _nsumOf(nvectors, h, Vector, Vector_kwds)
602 except (TypeError, ValueError) as x:
603 raise VectorError(nvectors=nvectors, Vector=Vector, cause=x)
606def _triangulate(point1, bearing1, point2, bearing2, height=None,
607 wrap=False, **LatLon_and_kwds):
608 # (INTERNAL) Locate a point given two known points and initial
609 # bearings from those points, see C{LatLon.triangulate} above
611 def _gc(p, b, _i_):
612 n = p.toNvector()
613 de = NorthPole.cross(n, raiser=_pole_).unit() # east vector @ n
614 dn = n.cross(de) # north vector @ n
615 s, c = sincos2d(Bearing(b, name=_bearing_ + _i_))
616 dest = de.times(s)
617 dnct = dn.times(c)
618 d = dnct.plus(dest) # direction vector @ n
619 return n.cross(d) # great circle point + bearing
621 if wrap:
622 point2 = _unrollon(point1, point2, wrap=wrap)
623 if _isequalTo(point1, point2, eps=EPS):
624 raise _ValueError(points=point2, wrap=wrap, txt=_coincident_)
626 gc1 = _gc(point1, bearing1, _1_) # great circle p1 + b1
627 gc2 = _gc(point2, bearing2, _2_) # great circle p2 + b2
629 n = gc1.cross(gc2, raiser=_point_) # n-vector of intersection point
630 h = point1._havg(point2, h=height)
631 kwds = _xkwds(LatLon_and_kwds, height=h)
632 return n.toLatLon(**kwds) # Nvector(n.x, n.y, n.z).toLatLon(...)
635def _trilaterate(point1, distance1, point2, distance2, point3, distance3,
636 radius=R_M, height=None, useZ=False,
637 wrap=False, **LatLon_and_kwds):
638 # (INTERNAL) Locate a point at given distances from
639 # three other points, see LatLon.triangulate above
641 def _nr2(p, d, r, _i_, *qs): # .toNvector and angular distance squared
642 for q in qs:
643 if _isequalTo(p, q, eps=EPS):
644 raise _ValueError(points=p, txt=_coincident_)
645 return p.toNvector(), (Scalar(d, name=_distance_ + _i_) / r)**2
647 p1, r = point1, Radius_(radius)
648 p2, p3, _ = _unrollon3(p1, point2, point3, wrap)
650 n1, r12 = _nr2(p1, distance1, r, _1_)
651 n2, r22 = _nr2(p2, distance2, r, _2_, p1)
652 n3, r32 = _nr2(p3, distance3, r, _3_, p1, p2)
654 # the following uses x,y coordinate system with origin at n1, x axis n1->n2
655 y = n3.minus(n1)
656 x = n2.minus(n1)
657 z = None
659 d = x.length # distance n1->n2
660 if d > EPS_2: # and y.length > EPS_2:
661 X = x.unit() # unit vector in x direction n1->n2
662 i = X.dot(y) # signed magnitude of x component of n1->n3
663 Y = y.minus(X.times(i)).unit() # unit vector in y direction
664 j = Y.dot(y) # signed magnitude of y component of n1->n3
665 if fabs(j) > EPS_2:
666 # courtesy of U{Carlos Freitas<https://GitHub.com/mrJean1/PyGeodesy/issues/33>}
667 x = fsumf_(r12, -r22, d**2) / (d * _2_0) # n1->intersection x- and ...
668 y = fsumf_(r12, -r32, i**2, j**2, x * i * _N_2_0) / (j * _2_0) # ... y-component
669 # courtesy of U{AleixDev<https://GitHub.com/mrJean1/PyGeodesy/issues/43>}
670 z = fsumf_(max(r12, r22, r32), -(x**2), -(y**2)) # XXX not just r12!
671 if z > EPS:
672 n = n1.plus(X.times(x)).plus(Y.times(y))
673 if useZ: # include Z component
674 Z = X.cross(Y) # unit vector perpendicular to plane
675 n = n.plus(Z.times(sqrt(z)))
676 if height is None:
677 h = fidw((point1.height, point2.height, point3.height),
678 map1(fabs, distance1, distance2, distance3))
679 else:
680 h = Height(height)
681 kwds = _xkwds(LatLon_and_kwds, height=h)
682 return n.toLatLon(**kwds) # Nvector(n.x, n.y, n.z).toLatLon(...)
684 # no intersection, d < EPS_2 or fabs(j) < EPS_2 or z < EPS
685 t = _SPACE_(_no_, _intersection_, NN)
686 raise IntersectionError(point1=point1, distance1=distance1,
687 point2=point2, distance2=distance2,
688 point3=point3, distance3=distance3,
689 txt=unstr(t, z=z, useZ=useZ, wrap=wrap))
692__all__ += _ALL_DOCS(LatLonNvectorBase, NvectorBase, sumOf) # classes
694# **) MIT License
695#
696# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved.
697#
698# Permission is hereby granted, free of charge, to any person obtaining a
699# copy of this software and associated documentation files (the "Software"),
700# to deal in the Software without restriction, including without limitation
701# the rights to use, copy, modify, merge, publish, distribute, sublicense,
702# and/or sell copies of the Software, and to permit persons to whom the
703# Software is furnished to do so, subject to the following conditions:
704#
705# The above copyright notice and this permission notice shall be included
706# in all copies or substantial portions of the Software.
707#
708# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
709# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
710# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
711# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
712# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
713# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
714# OTHER DEALINGS IN THE SOFTWARE.