Coverage for pygeodesy/vector3d.py: 97%
235 statements
« prev ^ index » next coverage.py v7.2.2, created at 2024-06-10 14:08 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2024-06-10 14:08 -0400
2# -*- coding: utf-8 -*-
4u'''Extended 3-D vector class L{Vector3d} and functions.
6Function L{intersection3d3}, L{intersections2}, L{parse3d}, L{sumOf},
7L{trilaterate2d2} and L{trilaterate3d2}.
8'''
10from pygeodesy.constants import EPS, EPS0, EPS1, EPS4, INT0, isnear0, \
11 _0_0, _1_0
12from pygeodesy.errors import IntersectionError, _ValueError, VectorError, \
13 _xattr, _xError, _xkwds, _xkwds_get, _xkwds_item2
14from pygeodesy.fmath import euclid, fabs, fdot, hypot, sqrt, fsum1_
15# from pygeodesy.fsums import fsum1_ # from .fmath
16# from pygeodesy.formy import _radical2 # in _intersects2 below
17from pygeodesy.interns import _COMMA_, _concentric_, _intersection_, \
18 _near_, _negative_, _no_, _too_
19from pygeodesy.iters import PointsIter, Fmt
20from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS
21from pygeodesy.named import _name__, _name2__, _xnamed, _xotherError
22from pygeodesy.namedTuples import Intersection3Tuple, NearestOn2Tuple, \
23 NearestOn6Tuple, Vector3Tuple # Vector4Tuple
24# from pygeodesy.nvectorBase import _nsumOf # _MODS
25# from pygeodesy.streprs import Fmt # from .iters
26from pygeodesy.units import _fi_j2, _isDegrees, Radius, Radius_
27from pygeodesy.utily import atan2b, sincos2d
28# import pygeodesy.vector2d as _vector2d # _MODS.into
29from pygeodesy.vector3dBase import Vector3dBase
31# from math import fabs, sqrt # from .fmath
33__all__ = _ALL_LAZY.vector3d
34__version__ = '24.06.06'
36_vector2d = _MODS.into(vector2d=__name__)
39class Vector3d(Vector3dBase):
40 '''Extended 3-D vector.
42 In a geodesy context, these may be used to represent:
43 - n-vector, the normal to a point on the earth's surface
44 - Earth-Centered, Earth-Fixed (ECEF) cartesian (== spherical n-vector)
45 - great circle normal to the vector
46 - motion vector on the earth's surface
47 - etc.
48 '''
50 def bearing(self, useZ=True):
51 '''Get this vector's "bearing", the angle off the +Z axis, clockwise.
53 @kwarg useZ: If C{True}, use the Z component, otherwise ignore the
54 Z component and consider the +Y as the +Z axis.
56 @return: Bearing (compass C{degrees}).
57 '''
58 x, y = self.x, self.y
59 if useZ:
60 x, y = hypot(x, y), self.z
61 return atan2b(x, y)
63 def circin6(self, point2, point3, eps=EPS4):
64 '''Return the radius and center of the I{inscribed} aka I{In- circle}
65 of a (3-D) triangle formed by this and two other points.
67 @arg point2: Second point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple},
68 C{Vector4Tuple} or C{Vector2Tuple} if C{B{useZ}=False}).
69 @arg point3: Third point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple},
70 C{Vector4Tuple} or C{Vector2Tuple} if C{B{useZ}=False}).
71 @kwarg eps: Tolerance for function L{pygeodesy.trilaterate3d2} if
72 C{B{useZ} is True} otherwise L{pygeodesy.trilaterate2d2}.
74 @return: L{Circin6Tuple}C{(radius, center, deltas, cA, cB, cC)}. The
75 C{center} and contact points C{cA}, C{cB} and C{cC}, each an
76 instance of this (sub-)class, are co-planar with this and the
77 two given points.
79 @raise ImportError: Package C{numpy} not found, not installed or older
80 than version 1.10.
82 @raise IntersectionError: Near-coincident or -colinear points or
83 a trilateration or C{numpy} issue.
85 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}.
87 @see: Function L{pygeodesy.circin6}, U{Incircle
88 <https://MathWorld.Wolfram.com/Incircle.html>} and U{Contact
89 Triangle<https://MathWorld.Wolfram.com/ContactTriangle.html>}.
90 '''
91 try:
92 return _vector2d._circin6(self, point2, point3, eps=eps, useZ=True)
93 except (AssertionError, TypeError, ValueError) as x:
94 raise _xError(x, point=self, point2=point2, point3=point3)
96 def circum3(self, point2, point3, circum=True, eps=EPS4):
97 '''Return the radius and center of the smallest circle I{through} or
98 I{containing} this and two other (3-D) points.
100 @arg point2: Second point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple}
101 or C{Vector4Tuple}).
102 @arg point3: Third point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple}
103 or C{Vector4Tuple}).
104 @kwarg circum: If C{True} return the C{circumradius} and C{circumcenter},
105 always, ignoring the I{Meeus}' Type I case (C{bool}).
106 @kwarg eps: Tolerance passed to function L{pygeodesy.trilaterate3d2}.
108 @return: A L{Circum3Tuple}C{(radius, center, deltas)}. The C{center}, an
109 instance of this (sub-)class, is co-planar with this and the two
110 given points.
112 @raise ImportError: Package C{numpy} not found, not installed or older than
113 version 1.10.
115 @raise IntersectionError: Near-concentric, -coincident or -colinear points
116 or a trilateration or C{numpy} issue.
118 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}.
120 @see: Function L{pygeodesy.circum3} and methods L{circum4_} and L{meeus2}.
121 '''
122 try:
123 return _vector2d._circum3(self, point2, point3, circum=circum,
124 eps=eps, useZ=True, clas=self.classof)
125 except (AssertionError, TypeError, ValueError) as x:
126 raise _xError(x, point=self, point2=point2, point3=point3, circum=circum)
128 def circum4_(self, *points):
129 '''Best-fit a sphere through this and two or more other (3-D) points.
131 @arg points: Other points (each a C{Cartesian}, L{Vector3d}, C{Vector3Tuple}
132 or C{Vector4Tuple}).
134 @return: L{Circum4Tuple}C{(radius, center, rank, residuals)} with C{center}
135 an instance if this (sub-)class.
137 @raise ImportError: Package C{numpy} not found, not installed or
138 older than version 1.10.
140 @raise NumPyError: Some C{numpy} issue.
142 @raise PointsError: Too few B{C{points}}.
144 @raise TypeError: One of the B{C{points}} invalid.
146 @see: Function L{pygeodesy.circum4_} and methods L{circum3} and L{meeus2}.
147 '''
148 return _vector2d.circum4_(self, *points, useZ=True, Vector=self.classof)
150 def iscolinearWith(self, point1, point2, eps=EPS):
151 '''Check whether this and two other (3-D) points are colinear.
153 @arg point1: One point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple}
154 or C{Vector4Tuple}).
155 @arg point2: An other point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple}
156 or C{Vector4Tuple}).
157 @kwarg eps: Tolerance (C{scalar}), same units as C{x},
158 C{y}, and C{z}.
160 @return: C{True} if this point is colinear with B{C{point1}} and
161 B{C{point2}}, C{False} otherwise.
163 @raise TypeError: Invalid B{C{point1}} or B{C{point2}}.
165 @see: Method L{nearestOn}.
166 '''
167 v = self if self.name else _otherV3d(NN_OK=False, this=self)
168 return _vector2d._iscolinearWith(v, point1, point2, eps=eps)
170 def meeus2(self, point2, point3, circum=False):
171 '''Return the radius and I{Meeus}' Type of the smallest circle I{through}
172 or I{containing} this and two other (3-D) points.
174 @arg point2: Second point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple}
175 or C{Vector4Tuple}).
176 @arg point3: Third point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple}
177 or C{Vector4Tuple}).
178 @kwarg circum: If C{True} return the C{circumradius} and C{circumcenter}
179 always, overriding I{Meeus}' Type II case (C{bool}).
181 @return: L{Meeus2Tuple}C{(radius, Type)}, with C{Type} the C{circumcenter}
182 iff C{B{circum}=True}.
184 @raise IntersectionError: Coincident or colinear points, iff C{B{circum}=True}.
186 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}.
188 @see: Function L{pygeodesy.meeus2} and methods L{circum3} and L{circum4_}.
189 '''
190 try:
191 return _vector2d._meeus2(self, point2, point3, circum, clas=self.classof)
192 except (TypeError, ValueError) as x:
193 raise _xError(x, point=self, point2=point2, point3=point3, circum=circum)
195 def nearestOn(self, point1, point2, within=True):
196 '''Locate the point between two points closest to this point.
198 @arg point1: Start point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple} or
199 C{Vector4Tuple}).
200 @arg point2: End point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple} or
201 C{Vector4Tuple}).
202 @kwarg within: If C{True} return the closest point between the given
203 points, otherwise the closest point on the extended
204 line through both points (C{bool}).
206 @return: Closest point, either B{C{point1}} or B{C{point2}} or an instance
207 of this (sub-)class.
209 @raise TypeError: Invalid B{C{point1}} or B{C{point2}}.
211 @see: Method L{sphericalTrigonometry.LatLon.nearestOn3} and U{3-D Point-Line
212 Distance<https://MathWorld.Wolfram.com/Point-LineDistance3-Dimensional.html>}.
213 '''
214 return _nearestOn2(self, point1, point2, within=within).closest
216 def nearestOn6(self, points, closed=False, useZ=True): # eps=EPS
217 '''Locate the point on a path or polygon closest to this point.
219 The closest point is either on and within the extent of a polygon
220 edge or the nearest of that edge's end points.
222 @arg points: The path or polygon points (C{Cartesian}, L{Vector3d},
223 C{Vector3Tuple} or C{Vector4Tuple}[]).
224 @kwarg closed: Optionally, close the path or polygon (C{bool}).
225 @kwarg useZ: If C{True}, use the Z components, otherwise force C{z=INT0} (C{bool}).
227 @return: A L{NearestOn6Tuple}C{(closest, distance, fi, j, start, end)}
228 with the C{closest}, the C{start} and the C{end} point each
229 an instance of this point's (sub-)class.
231 @raise PointsError: Insufficient number of B{C{points}}
233 @raise TypeError: Non-cartesian B{C{points}}.
235 @note: Distances measured with method L{Vector3d.equirectangular}.
237 @see: Function L{nearestOn6}.
238 '''
239 return nearestOn6(self, points, closed=closed, useZ=useZ) # Vector=self.classof
241 def parse(self, str3d, sep=_COMMA_, **name):
242 '''Parse an C{"x, y, z"} string to a L{Vector3d} instance.
244 @arg str3d: X, y and z string (C{str}), see function L{parse3d}.
245 @kwarg sep: Optional separator (C{str}).
246 @kwarg name: Optional instance C{B{name}=NN} (C{str}), overriding this name.
248 @return: The instance (L{Vector3d}).
250 @raise VectorError: Invalid B{C{str3d}}.
251 '''
252 return parse3d(str3d, sep=sep, Vector=self.classof, name=self._name__(name))
254 def radii11(self, point2, point3):
255 '''Return the radii of the C{Circum-}, C{In-}, I{Soddy} and C{Tangent}
256 circles of a (3-D) triangle.
258 @arg point2: Second point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple},
259 C{Vector4Tuple} or C{Vector2Tuple} if C{B{useZ}=False}).
260 @arg point3: Third point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple},
261 C{Vector4Tuple} or C{Vector2Tuple} if C{B{useZ}=False}).
263 @return: L{Radii11Tuple}C{(rA, rB, rC, cR, rIn, riS, roS, a, b, c, s)}.
265 @raise TriangleError: Near-coincident or -colinear points.
267 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}.
269 @see: Function L{pygeodesy.radii11}, U{Incircle
270 <https://MathWorld.Wolfram.com/Incircle.html>}, U{Soddy Circles
271 <https://MathWorld.Wolfram.com/SoddyCircles.html>} and U{Tangent
272 Circles<https://MathWorld.Wolfram.com/TangentCircles.html>}.
273 '''
274 try:
275 return _vector2d._radii11ABC(self, point2, point3, useZ=True)[0]
276 except (TypeError, ValueError) as x:
277 raise _xError(x, point=self, point2=point2, point3=point3)
279 def soddy4(self, point2, point3, eps=EPS4):
280 '''Return the radius and center of the C{inner} I{Soddy} circle of a
281 (3-D) triangle.
283 @arg point2: Second point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple},
284 C{Vector4Tuple} or C{Vector2Tuple} if C{B{useZ}=False}).
285 @arg point3: Third point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple},
286 C{Vector4Tuple} or C{Vector2Tuple} if C{B{useZ}=False}).
287 @kwarg eps: Tolerance for function L{pygeodesy.trilaterate3d2} if
288 C{B{useZ} is True} otherwise L{pygeodesy.trilaterate2d2}.
290 @return: L{Soddy4Tuple}C{(radius, center, deltas, outer)}. The C{center},
291 an instance of B{C{point1}}'s (sub-)class, is co-planar with the
292 three given points.
294 @raise ImportError: Package C{numpy} not found, not installed or older
295 than version 1.10.
297 @raise IntersectionError: Near-coincident or -colinear points or
298 a trilateration or C{numpy} issue.
300 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}.
302 @see: Function L{pygeodesy.soddy4}.
303 '''
304 return _vector2d.soddy4(self, point2, point3, eps=eps, useZ=True)
306 def trilaterate2d2(self, radius, center2, radius2, center3, radius3, eps=EPS4, z=INT0):
307 '''Trilaterate this and two other circles, each given as a (2-D) center
308 and a radius.
310 @arg radius: Radius of this circle (same C{units} as this C{x} and C{y}.
311 @arg center2: Center of the 2nd circle (C{Cartesian}, L{Vector3d},
312 C{Vector2Tuple}, C{Vector3Tuple} or C{Vector4Tuple}).
313 @arg radius2: Radius of this circle (same C{units} as this C{x} and C{y}.
314 @arg center3: Center of the 3rd circle (C{Cartesian}, L{Vector3d},
315 C{Vector2Tuple}, C{Vector3Tuple} or C{Vector4Tuple}).
316 @arg radius3: Radius of the 3rd circle (same C{units} as this C{x} and C{y}.
317 @kwarg eps: Tolerance to check the trilaterated point I{delta} on all
318 3 circles (C{scalar}) or C{None} for no checking.
319 @kwarg z: Optional Z component of the trilaterated point (C{scalar}).
321 @return: Trilaterated point, an instance of this (sub-)class with C{z=B{z}}.
323 @raise IntersectionError: No intersection, near-concentric or -colinear
324 centers, trilateration failed some other way
325 or the trilaterated point is off one circle
326 by more than B{C{eps}}.
328 @raise TypeError: Invalid B{C{center2}} or B{C{center3}}.
330 @raise UnitError: Invalid B{C{radius1}}, B{C{radius2}} or B{C{radius3}}.
332 @see: Function L{pygeodesy.trilaterate2d2}.
333 '''
335 def _xyr3(r, **name_v):
336 v = _otherV3d(useZ=False, **name_v)
337 return v.x, v.y, r
339 try:
340 return _vector2d._trilaterate2d2(*(_xyr3(radius, center=self) +
341 _xyr3(radius2, center2=center2) +
342 _xyr3(radius3, center3=center3)),
343 eps=eps, Vector=self.classof, z=z)
344 except (AssertionError, TypeError, ValueError) as x:
345 raise _xError(x, center=self, radius=radius,
346 center2=center2, radius2=radius2,
347 center3=center3, radius3=radius3)
349 def trilaterate3d2(self, radius, center2, radius2, center3, radius3, eps=EPS4):
350 '''Trilaterate this and two other spheres, each given as a (3-D) center
351 and a radius.
353 @arg radius: Radius of this sphere (same C{units} as this C{x}, C{y}
354 and C{z}).
355 @arg center2: Center of the 2nd sphere (C{Cartesian}, L{Vector3d},
356 C{Vector3Tuple} or C{Vector4Tuple}).
357 @arg radius2: Radius of this sphere (same C{units} as this C{x}, C{y}
358 and C{z}).
359 @arg center3: Center of the 3rd sphere (C{Cartesian}, , L{Vector3d},
360 C{Vector3Tuple} or C{Vector4Tuple}).
361 @arg radius3: Radius of the 3rd sphere (same C{units} as this C{x}, C{y}
362 and C{z}).
363 @kwarg eps: Pertubation tolerance (C{scalar}), same units as C{x}, C{y}
364 and C{z} or C{None} for no pertubations.
366 @return: 2-Tuple with two trilaterated points, each an instance of this
367 (sub-)class. Both points are the same instance if all three
368 spheres intersect or abut in a single point.
370 @raise ImportError: Package C{numpy} not found, not installed or
371 older than version 1.10.
373 @raise IntersectionError: Near-concentric, -colinear, too distant or
374 non-intersecting spheres or C{numpy} issue.
376 @raise NumPyError: Some C{numpy} issue.
378 @raise TypeError: Invalid B{C{center2}} or B{C{center3}}.
380 @raise UnitError: Invalid B{C{radius}}, B{C{radius2}} or B{C{radius3}}.
382 @note: Package U{numpy<https://PyPI.org/project/numpy>} is required,
383 version 1.10 or later.
385 @see: Norrdine, A. U{I{An Algebraic Solution to the Multilateration
386 Problem}<https://www.ResearchGate.net/publication/275027725>}
387 and U{I{implementation}<https://www.ResearchGate.net/publication/288825016>}.
388 '''
389 try:
390 c1 = _otherV3d(center=self, NN_OK=False)
391 return _vector2d._trilaterate3d2(c1, Radius_(radius, low=eps),
392 center2, radius2,
393 center3, radius3,
394 eps=eps, clas=self.classof)
395 except (AssertionError, TypeError, ValueError) as x:
396 raise _xError(x, center=self, radius=radius,
397 center2=center2, radius2=radius2,
398 center3=center3, radius3=radius3)
401def _intersect3d3(start1, end1, start2, end2, eps=EPS, useZ=False): # MCCABE 16 in .formy.intersection2, .rhumbBase
402 # (INTERNAL) Intersect two lines, see L{intersection3d3} below,
403 # separated to allow callers to embellish any exceptions
405 def _corners2(s1, b1, s2, useZ):
406 # Get the C{s1'} and C{e1'} corners of a right-angle
407 # triangle with the hypotenuse thru C{s1} at bearing
408 # C{b1} and the right angle at C{s2}
409 dx, dy, d = s2.minus(s1).xyz
410 if useZ and not isnear0(d): # not supported
411 raise IntersectionError(useZ=d, bearing=b1)
412 s, c = sincos2d(b1)
413 if s and c:
414 dx *= c / s
415 dy *= s / c
416 e1 = Vector3d(s2.x, s1.y + dx, s1.z)
417 s1 = Vector3d(s1.x + dy, s2.y, s1.z)
418 else: # orthogonal
419 d = euclid(dx, dy) # hypot?
420 e1 = Vector3d(s1.x + s * d, s1.y + c * d, s1.z)
421 return s1, e1
423 def _outside(t, d2, o): # -o before start#, +o after end#
424 return -o if t < 0 else (o if t > d2 else 0) # XXX d2 + eps?
426 s1 = t = _otherV3d(useZ=useZ, start1=start1)
427 s2 = _otherV3d(useZ=useZ, start2=start2)
428 b1 = _isDegrees(end1)
429 if b1: # bearing, make an e1
430 s1, e1 = _corners2(s1, end1, s2, useZ)
431 else:
432 e1 = _otherV3d(useZ=useZ, end1=end1)
433 b2 = _isDegrees(end2)
434 if b2: # bearing, make an e2
435 s2, e2 = _corners2(s2, end2, t, useZ)
436 else:
437 e2 = _otherV3d(useZ=useZ, end2=end2)
439 a = e1.minus(s1)
440 b = e2.minus(s2)
441 c = s2.minus(s1)
443 ab = a.cross(b)
444 d = fabs(c.dot(ab))
445 e = max(EPS0, eps or _0_0)
446 if d > EPS0 and ab.length > e: # PYCHOK no cover
447 d = d / ab.length # /= chokes PyChecker
448 if d > e: # argonic, skew lines distance
449 raise IntersectionError(skew_d=d, txt=_no_(_intersection_))
451 # co-planar, non-skew lines
452 ab2 = ab.length2
453 if ab2 < e: # colinear, parallel or null line(s)
454 x = a.length2 > b.length2
455 if x: # make C{a} the shortest
456 a, b = b, a
457 s1, s2 = s2, s1
458 e1, e2 = e2, e1
459 b1, b2 = b2, b1
460 if b.length2 < e: # PYCHOK no cover
461 if c.length < e:
462 return s1, 0, 0
463 elif e2.minus(e1).length < e:
464 return e1, 0, 0
465 elif a.length2 < e: # null (s1, e1), non-null (s2, e2)
466 # like _nearestOn2(s1, s2, e2, within=False, eps=e)
467 t = s1.minus(s2).dot(b)
468 v = s2.plus(b.times(t / b.length2))
469 if s1.minus(v).length < e:
470 o = 0 if b2 else _outside(t, b.length2, 1 if x else 2)
471 return (v, o, 0) if x else (v, 0, o)
472 raise IntersectionError(length2=ab2, txt=_no_(_intersection_))
474 cb = c.cross(b)
475 t = cb.dot(ab)
476 o1 = 0 if b1 else _outside(t, ab2, 1)
477 v = s1.plus(a.times(t / ab2))
478 o2 = 0 if b2 else _outside(v.minus(s2).dot(b), b.length2, 2)
479 return v, o1, o2
482def intersection3d3(start1, end1, start2, end2, eps=EPS, useZ=True,
483 **Vector_and_kwds):
484 '''Compute the intersection point of two (2- or 3-D) lines, each defined
485 by two points or by a point and a bearing.
487 @arg start1: Start point of the first line (C{Cartesian}, L{Vector3d},
488 C{Vector3Tuple} or C{Vector4Tuple}).
489 @arg end1: End point of the first line (C{Cartesian}, L{Vector3d},
490 C{Vector3Tuple} or C{Vector4Tuple}) or the bearing at
491 B{C{start1}} (compass C{degrees}).
492 @arg start2: Start point of the second line (C{Cartesian}, L{Vector3d},
493 C{Vector3Tuple} or C{Vector4Tuple}).
494 @arg end2: End point of the second line (C{Cartesian}, L{Vector3d},
495 C{Vector3Tuple} or C{Vector4Tuple}) or the bearing at
496 B{C{start2}} (Ccompass C{degrees}).
497 @kwarg eps: Tolerance for skew line distance and length (C{EPS}).
498 @kwarg useZ: If C{True}, use the Z components, otherwise force C{z=INT0} (C{bool}).
499 @kwarg Vector_and_kwds: Optional class C{B{Vector}=None} to return the
500 intersection points and optional, additional B{C{Vector}}
501 keyword arguments, otherwise B{C{start1}}'s (sub-)class.
503 @return: An L{Intersection3Tuple}C{(point, outside1, outside2)} with
504 C{point} an instance of B{C{Vector}} or B{C{start1}}'s (sub-)class.
506 @note: The C{outside} values is C{0} for lines specified by point and bearing.
508 @raise IntersectionError: Invalid, skew, non-co-planar or otherwise
509 non-intersecting lines.
511 @see: U{Line-line intersection<https://MathWorld.Wolfram.com/Line-LineIntersection.html>}
512 and U{line-line distance<https://MathWorld.Wolfram.com/Line-LineDistance.html>},
513 U{skew lines<https://MathWorld.Wolfram.com/SkewLines.html>} and U{point-line
514 distance<https://MathWorld.Wolfram.com/Point-LineDistance3-Dimensional.html>}.
515 '''
516 try:
517 v, o1, o2 = _intersect3d3(start1, end1, start2, end2, eps=eps, useZ=useZ)
518 except (TypeError, ValueError) as x:
519 raise _xError(x, start1=start1, end1=end1, start2=start2, end2=end2)
520 v = _nVc(v, **_xkwds(Vector_and_kwds, clas=start1.classof,
521 name=intersection3d3.__name__))
522 return Intersection3Tuple(v, o1, o2)
525def intersections2(center1, radius1, center2, radius2, sphere=True, **Vector_and_kwds):
526 '''Compute the intersection of two spheres or circles, each defined by a (3-D)
527 center point and a radius.
529 @arg center1: Center of the first sphere or circle (C{Cartesian}, L{Vector3d},
530 C{Vector3Tuple} or C{Vector4Tuple}).
531 @arg radius1: Radius of the first sphere or circle (same units as the
532 B{C{center1}} coordinates).
533 @arg center2: Center of the second sphere or circle (C{Cartesian}, L{Vector3d},
534 C{Vector3Tuple} or C{Vector4Tuple}).
535 @arg radius2: Radius of the second sphere or circle (same units as the
536 B{C{center1}} and B{C{center2}} coordinates).
537 @kwarg sphere: If C{True} compute the center and radius of the intersection of
538 two spheres. If C{False}, ignore the C{z}-component and compute
539 the intersection of two circles (C{bool}).
540 @kwarg Vector_and_kwds: Optional class C{B{Vector}=None} to return the
541 intersection points and optional, additional B{C{Vector}}
542 keyword arguments, otherwise B{C{center1}}'s (sub-)class.
544 @return: If B{C{sphere}} is C{True}, a 2-tuple of the C{center} and C{radius}
545 of the intersection of the I{spheres}. The C{radius} is C{0.0} for
546 abutting spheres (and the C{center} is aka the I{radical center}).
548 If B{C{sphere}} is C{False}, a 2-tuple with the two intersection
549 points of the I{circles}. For abutting circles, both points are
550 the same instance, aka the I{radical center}.
552 @raise IntersectionError: Concentric, invalid or non-intersecting spheres
553 or circles.
555 @raise TypeError: Invalid B{C{center1}} or B{C{center2}}.
557 @raise UnitError: Invalid B{C{radius1}} or B{C{radius2}}.
559 @see: U{Sphere-Sphere<https://MathWorld.Wolfram.com/Sphere-SphereIntersection.html>} and
560 U{Circle-Circle<https://MathWorld.Wolfram.com/Circle-CircleIntersection.html>}
561 Intersection.
562 '''
563 try:
564 return _intersects2(center1, Radius_(radius1=radius1),
565 center2, Radius_(radius2=radius2), sphere=sphere,
566 clas=center1.classof, **Vector_and_kwds)
567 except (TypeError, ValueError) as x:
568 raise _xError(x, center1=center1, radius1=radius1, center2=center2, radius2=radius2)
571def _intersects2(center1, r1, center2, r2, sphere=True, too_d=None, # in CartesianEllipsoidalBase.intersections2,
572 **clas_Vector_and_kwds): # .ellipsoidalBaseDI._intersections2, .formy.intersections2
573 # (INTERNAL) Intersect two spheres or circles, see L{intersections2}
574 # above, separated to allow callers to embellish any exceptions
576 def _nV3(x, y, z):
577 v = Vector3d(x, y, z)
578 n = intersections2.__name__
579 return _nVc(v, **_xkwds(clas_Vector_and_kwds, name=n))
581 def _xV3(c1, u, x, y):
582 xy1 = x, y, _1_0 # transform to original space
583 return _nV3(fdot(xy1, u.x, -u.y, c1.x),
584 fdot(xy1, u.y, u.x, c1.y), _0_0)
586 c1 = _otherV3d(useZ=sphere, center1=center1)
587 c2 = _otherV3d(useZ=sphere, center2=center2)
589 if r1 < r2: # r1, r2 == R, r
590 c1, c2 = c2, c1
591 r1, r2 = r2, r1
593 m = c2.minus(c1)
594 d = m.length
595 if d < max(r2 - r1, EPS):
596 raise IntersectionError(_near_(_concentric_)) # XXX ConcentricError?
598 o = fsum1_(-d, r1, r2) # overlap == -(d - (r1 + r2))
599 # compute intersections with c1 at (0, 0) and c2 at (d, 0), like
600 # <https://MathWorld.Wolfram.com/Circle-CircleIntersection.html>
601 if o > EPS: # overlapping, r1, r2 == R, r
602 x = _MODS.formy._radical2(d, r1, r2).xline
603 y = _1_0 - (x / r1)**2
604 if y > EPS:
605 y = r1 * sqrt(y) # y == a / 2
606 elif y < 0: # PYCHOK no cover
607 raise IntersectionError(_negative_)
608 else: # abutting
609 y = _0_0
610 elif o < 0: # PYCHOK no cover
611 if too_d is not None:
612 d = too_d
613 raise IntersectionError(_too_(Fmt.distant(d)))
614 else: # abutting
615 x, y = r1, _0_0
617 u = m.unit()
618 if sphere: # sphere center and radius
619 c = c1 if x < EPS else (
620 c2 if x > EPS1 else c1.plus(u.times(x)))
621 t = _nV3(c.x, c.y, c.z), Radius(y)
623 elif y > 0: # intersecting circles
624 t = _xV3(c1, u, x, y), _xV3(c1, u, x, -y)
625 else: # abutting circles
626 t = _xV3(c1, u, x, 0)
627 t = t, t
628 return t
631def iscolinearWith(point, point1, point2, eps=EPS, useZ=True):
632 '''Check whether a point is colinear with two other (2- or 3-D) points.
634 @arg point: The point (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}).
635 @arg point1: First point (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}).
636 @arg point2: Second point (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}).
637 @kwarg eps: Tolerance (C{scalar}), same units as C{x}, C{y} and C{z}.
638 @kwarg useZ: If C{True}, use the Z components, otherwise force C{z=INT0} (C{bool}).
640 @return: C{True} if B{C{point}} is colinear B{C{point1}} and B{C{point2}},
641 C{False} otherwise.
643 @raise TypeError: Invalid B{C{point}}, B{C{point1}} or B{C{point2}}.
645 @see: Function L{nearestOn}.
646 '''
647 p = _otherV3d(useZ=useZ, point=point)
648 return _vector2d._iscolinearWith(p, point1, point2, eps=eps, useZ=useZ)
651def nearestOn(point, point1, point2, within=True, useZ=True, Vector=None, **Vector_kwds):
652 '''Locate the point between two points closest to a reference (2- or 3-D).
654 @arg point: Reference point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple}
655 or C{Vector4Tuple}).
656 @arg point1: Start point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple} or
657 C{Vector4Tuple}).
658 @arg point2: End point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple} or
659 C{Vector4Tuple}).
660 @kwarg within: If C{True} return the closest point between both given
661 points, otherwise the closest point on the extended line
662 through both points (C{bool}).
663 @kwarg useZ: If C{True}, use the Z components, otherwise force C{z=INT0} (C{bool}).
664 @kwarg Vector: Class to return closest point (C{Cartesian}, L{Vector3d}
665 or C{Vector3Tuple}) or C{None}.
666 @kwarg Vector_kwds: Optional, additional B{C{Vector}} keyword arguments,
667 ignored if C{B{Vector} is None}.
669 @return: Closest point, either B{C{point1}} or B{C{point2}} or an instance
670 of the B{C{point}}'s (sub-)class or B{C{Vector}} if not C{None}.
672 @raise TypeError: Invalid B{C{point}}, B{C{point1}} or B{C{point2}}.
674 @see: U{3-D Point-Line Distance<https://MathWorld.Wolfram.com/Point-LineDistance3-Dimensional.html>},
675 C{Cartesian} and C{LatLon} methods C{nearestOn}, method L{sphericalTrigonometry.LatLon.nearestOn3}
676 and function L{sphericalTrigonometry.nearestOn3}.
677 '''
678 p0 = _otherV3d(useZ=useZ, point =point)
679 p1 = _otherV3d(useZ=useZ, point1=point1)
680 p2 = _otherV3d(useZ=useZ, point2=point2)
682 p, _ = _nearestOn2(p0, p1, p2, within=within)
683 if Vector is not None:
684 p = Vector(p.x, p.y, **_xkwds(Vector_kwds, z=p.z, name__=nearestOn))
685 elif p is p1:
686 p = point1
687 elif p is p2:
688 p = point2
689 else: # ignore Vector_kwds
690 p = point.classof(p.x, p.y, _xkwds_get(Vector_kwds, z=p.z), name__=nearestOn)
691 return p
694def _nearestOn2(p0, p1, p2, within=True, eps=EPS):
695 # (INTERNAL) Closest point and fraction, see L{nearestOn} above,
696 # separated to allow callers to embellish any exceptions
697 p21 = p2.minus(p1)
698 d2 = p21.length2
699 if d2 < eps: # coincident
700 p = p1 # ~= p2
701 t = 0
702 else: # see comments in .points.nearestOn5
703 t = p0.minus(p1).dot(p21) / d2
704 if within and t < eps:
705 p = p1
706 t = 0
707 elif within and t > (_1_0 - eps):
708 p = p2
709 t = 1
710 else:
711 p = p1.plus(p21.times(t))
712 return NearestOn2Tuple(p, t)
715def nearestOn6(point, points, closed=False, useZ=True, **Vector_and_kwds): # eps=EPS
716 '''Locate the point on a path or polygon closest to a reference point.
718 The closest point on each polygon edge is either the nearest of that
719 edge's end points or a point in between.
721 @arg point: Reference point (C{Cartesian}, L{Vector3d}, C{Vector3Tuple} or
722 C{Vector4Tuple}).
723 @arg points: The path or polygon points (C{Cartesian}, L{Vector3d},
724 C{Vector3Tuple} or C{Vector4Tuple}[]).
725 @kwarg closed: Optionally, close the path or polygon (C{bool}).
726 @kwarg useZ: If C{True}, use the Z components, otherwise force C{z=INT0} (C{bool}).
727 @kwarg Vector_and_kwds: Optional class C{B{Vector}=None} to return the closest
728 point and optional, additional B{C{Vector}} keyword
729 arguments, otherwise B{C{point}}'s (sub-)class.
731 @return: A L{NearestOn6Tuple}C{(closest, distance, fi, j, start, end)} with the
732 C{closest}, the C{start} and the C{end} point each an instance of the
733 B{C{Vector}} keyword argument of if {B{Vector}=None} or not specified,
734 an instance of the reference B{C{point}}'s (sub-)class.
736 @raise PointsError: Insufficient number of B{C{points}}
738 @raise TypeError: Non-cartesian B{C{point}} and B{C{points}}.
740 @note: Distances measured with method L{Vector3d.equirectangular}. For
741 geodetic distances use function L{nearestOn5} or one of the
742 C{LatLon.nearestOn6} methods.
743 '''
744 r = _otherV3d(useZ=useZ, point=point)
745 D2 = r.equirectangular # distance squared
747 Ps = PointsIter(points, loop=1, name=nearestOn6.__name__)
748 p1 = c = s = e = _otherV3d(useZ=useZ, i=0, points=Ps[0])
749 c2 = D2(c) # == r.minus(c).length2
751 f = i = 0 # p1..p2 == points[i]..[j]
752 for j, p2 in Ps.enumerate(closed=closed):
753 p2 = _otherV3d(useZ=useZ, i=j, points=p2)
754 p, t = _nearestOn2(r, p1, p2) # within=True, eps=EPS
755 d2 = D2(p) # == r.minus(p).length2
756 if d2 < c2:
757 c2, c, s, e, f = d2, p, p1, p2, (i + t)
758 p1, i = p2, j
760 f, j = _fi_j2(f, len(Ps)) # like .ellipsoidalBaseDI._nearestOn2_
762 kwds = _xkwds(Vector_and_kwds, clas=point.classof, name=Ps.name)
763 v = _nVc(c, **kwds)
764 s = _nVc(s, **kwds) if s is not c else v
765 e = _nVc(e, **kwds) if e is not c else v
766 return NearestOn6Tuple(v, sqrt(c2), f, j, s, e)
769def _nVc(v, clas=None, Vector=None, **Vector_kwds_name): # in .vector2d
770 # return a named C{Vector} or C{clas} instance
771 name, Vector_kwds = _name2__(**Vector_kwds_name)
772 if Vector is not None:
773 v = Vector(v.x, v.y, v.z, **Vector_kwds)
774 elif clas is not None:
775 v = clas(v.x, v.y, v.z) # ignore Vector_kwds
776 return _xnamed(v, name) if name else v
779def _otherV3d(useZ=True, NN_OK=True, i=None, **name_v):
780 # check named vector instance, return Vector3d
781 n, v = _xkwds_item2(name_v)
782 if useZ and isinstance(v, Vector3dBase):
783 return v if NN_OK or v.name else v.copy(name=Fmt.INDEX(n, i))
785 n = Fmt.INDEX(n, i)
786 try:
787 return Vector3d(v.x, v.y, (v.z if useZ else INT0), name=n)
788 except AttributeError: # no .x, .y or .z attr
789 pass
790 raise _xotherError(Vector3d(0, 0, 0), v, name=n, up=2)
793def parse3d(str3d, sep=_COMMA_, Vector=Vector3d, **Vector_kwds):
794 '''Parse an C{"x, y, z"} string.
796 @arg str3d: X, y and z values (C{str}).
797 @kwarg sep: Optional separator (C{str}).
798 @kwarg Vector: Optional class (L{Vector3d}).
799 @kwarg Vector_kwds: Optional B{C{Vector}} keyword arguments,
800 ignored if C{B{Vector} is None}.
802 @return: A B{C{Vector}} instance or if B{C{Vector}} is C{None},
803 a named L{Vector3Tuple}C{(x, y, z)}.
805 @raise VectorError: Invalid B{C{str3d}}.
806 '''
807 try:
808 v = [float(v.strip()) for v in str3d.split(sep)]
809 n = len(v)
810 if n != 3:
811 raise _ValueError(len=n)
812 except (TypeError, ValueError) as x:
813 raise VectorError(str3d=str3d, cause=x)
814 return _xnamed((Vector3Tuple(v) if Vector is None else # *v
815 Vector(*v, **Vector_kwds)), name__=parse3d) # .__name__
818def sumOf(vectors, Vector=Vector3d, **Vector_kwds):
819 '''Compute the I{vectorial} sum of two oe more vectors.
821 @arg vectors: Vectors to be added (L{Vector3d}[]).
822 @kwarg Vector: Optional class for the vectorial sum (L{Vector3d}).
823 @kwarg Vector_kwds: Optional B{C{Vector}} keyword arguments,
824 ignored if C{B{Vector} is None}.
826 @return: Vectorial sum as B{C{Vector}} or if B{C{Vector}} is
827 C{None}, a named L{Vector3Tuple}C{(x, y, z)}.
829 @raise VectorError: No B{C{vectors}}.
830 '''
831 try:
832 t = _MODS.nvectorBase._nsumOf(vectors, 0, None, {}) # no H
833 except (TypeError, ValueError) as x:
834 raise VectorError(vectors=vectors, Vector=Vector, cause=x)
835 x, y, z = t[:3]
836 return Vector3Tuple(x, y, z, name__=sumOf) if Vector is None else \
837 Vector(x, y, z, **_xkwds(Vector_kwds, name__=sumOf)) # .__name__
840def trilaterate2d2(x1, y1, radius1, x2, y2, radius2, x3, y3, radius3,
841 eps=None, **Vector_and_kwds):
842 '''Trilaterate three circles, each given as a (2-D) center and a radius.
844 @arg x1: Center C{x} coordinate of the 1st circle (C{scalar}).
845 @arg y1: Center C{y} coordinate of the 1st circle (C{scalar}).
846 @arg radius1: Radius of the 1st circle (C{scalar}).
847 @arg x2: Center C{x} coordinate of the 2nd circle (C{scalar}).
848 @arg y2: Center C{y} coordinate of the 2nd circle (C{scalar}).
849 @arg radius2: Radius of the 2nd circle (C{scalar}).
850 @arg x3: Center C{x} coordinate of the 3rd circle (C{scalar}).
851 @arg y3: Center C{y} coordinate of the 3rd circle (C{scalar}).
852 @arg radius3: Radius of the 3rd circle (C{scalar}).
853 @kwarg eps: Tolerance to check the trilaterated point I{delta} on all
854 3 circles (C{scalar}) or C{None} for no checking.
855 @kwarg Vector_and_kwds: Optional class C{B{Vector}=None} to return the
856 trilateration and optional, additional B{C{Vector}}
857 keyword arguments, otherwise (L{Vector3d}).
859 @return: Trilaterated point as C{B{Vector}(x, y, **B{Vector_kwds})}
860 or L{Vector2Tuple}C{(x, y)} if C{B{Vector} is None}..
862 @raise IntersectionError: No intersection, near-concentric or -colinear
863 centers, trilateration failed some other way
864 or the trilaterated point is off one circle
865 by more than B{C{eps}}.
867 @raise UnitError: Invalid B{C{radius1}}, B{C{radius2}} or B{C{radius3}}.
869 @see: U{Issue #49<https://GitHub.com/mrJean1/PyGeodesy/issues/49>},
870 U{Find X location using 3 known (X,Y) location using trilateration
871 <https://math.StackExchange.com/questions/884807>} and function
872 L{pygeodesy.trilaterate3d2}.
873 '''
874 return _vector2d._trilaterate2d2(x1, y1, radius1,
875 x2, y2, radius2,
876 x3, y3, radius3, eps=eps, **Vector_and_kwds)
879def trilaterate3d2(center1, radius1, center2, radius2, center3, radius3,
880 eps=EPS, **Vector_and_kwds):
881 '''Trilaterate three spheres, each given as a (3-D) center and a radius.
883 @arg center1: Center of the 1st sphere (C{Cartesian}, L{Vector3d},
884 C{Vector3Tuple} or C{Vector4Tuple}).
885 @arg radius1: Radius of the 1st sphere (same C{units} as C{x}, C{y}
886 and C{z}).
887 @arg center2: Center of the 2nd sphere (C{Cartesian}, L{Vector3d},
888 C{Vector3Tuple} or C{Vector4Tuple}).
889 @arg radius2: Radius of this sphere (same C{units} as C{x}, C{y}
890 and C{z}).
891 @arg center3: Center of the 3rd sphere (C{Cartesian}, L{Vector3d},
892 C{Vector3Tuple} or C{Vector4Tuple}).
893 @arg radius3: Radius of the 3rd sphere (same C{units} as C{x}, C{y}
894 and C{z}).
895 @kwarg eps: Pertubation tolerance (C{scalar}), same units as C{x},
896 C{y} and C{z} or C{None} for no pertubations.
897 @kwarg Vector_and_kwds: Optional class C{B{Vector}=None} to return the
898 trilateration and optional, additional B{C{Vector}}
899 keyword arguments, otherwise B{C{center1}}'s
900 (sub-)class.
902 @return: 2-Tuple with two trilaterated points, each a B{C{Vector}}
903 instance. Both points are the same instance if all three
904 spheres abut/intersect in a single point.
906 @raise ImportError: Package C{numpy} not found, not installed or
907 older than version 1.10.
909 @raise IntersectionError: Near-concentric, -colinear, too distant or
910 non-intersecting spheres.
912 @raise NumPyError: Some C{numpy} issue.
914 @raise TypeError: Invalid B{C{center1}}, B{C{center2}} or B{C{center3}}.
916 @raise UnitError: Invalid B{C{radius1}}, B{C{radius2}} or B{C{radius3}}.
918 @see: Norrdine, A. U{I{An Algebraic Solution to the Multilateration
919 Problem}<https://www.ResearchGate.net/publication/275027725>},
920 the U{I{implementation}<https://www.ResearchGate.net/publication/
921 288825016>} and function L{pygeodesy.trilaterate2d2}.
922 '''
923 try:
924 return _vector2d._trilaterate3d2(_otherV3d(center1=center1, NN_OK=False),
925 Radius_(radius1=radius1, low=eps),
926 center2, radius2, center3, radius3, eps=eps,
927 clas=center1.classof, **Vector_and_kwds)
928 except (AssertionError, TypeError, ValueError) as x:
929 raise _xError(x, center1=center1, radius1=radius1,
930 center2=center2, radius2=radius2,
931 center3=center3, radius3=radius3)
934def _xyzhdlln4(xyz, height, datum, ll=None, **name): # in .cartesianBase, .nvectorBase
935 '''(INTERNAL) Get a C{(h, d, ll, name)} 4-tuple.
936 '''
937 _x = _xattr
938 h = height or _x(xyz, height=None) or _x(xyz, h=None) or _x(ll, height=None)
939 d = datum or _x(xyz, datum=None) or _x(ll, datum=None)
940 return h, d, ll, _name__(name, _or_nameof=ll)
943__all__ += _ALL_DOCS(intersections2, sumOf, Vector3dBase)
945# **) MIT License
946#
947# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
948#
949# Permission is hereby granted, free of charge, to any person obtaining a
950# copy of this software and associated documentation files (the "Software"),
951# to deal in the Software without restriction, including without limitation
952# the rights to use, copy, modify, merge, publish, distribute, sublicense,
953# and/or sell copies of the Software, and to permit persons to whom the
954# Software is furnished to do so, subject to the following conditions:
955#
956# The above copyright notice and this permission notice shall be included
957# in all copies or substantial portions of the Software.
958#
959# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
960# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
961# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
962# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
963# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
964# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
965# OTHER DEALINGS IN THE SOFTWARE.