Coverage for pygeodesy/vector3dBase.py: 93%
274 statements
« prev ^ index » next coverage.py v7.2.2, created at 2024-03-10 16:39 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2024-03-10 16:39 -0400
2# -*- coding: utf-8 -*-
4u'''(INTERNAL) Private, 3-D vector base class C{Vector3dBase}.
6A pure Python implementation of vector-based functions by I{(C) Chris Veness
72011-2015} published under the same MIT Licence**, see U{Vector-based geodesy
8<https://www.Movable-Type.co.UK/scripts/latlong-vectors.html>}.
9'''
11from pygeodesy.basics import _copysign, islistuple, isscalar, map1, \
12 map2, _zip
13from pygeodesy.constants import EPS, EPS0, INT0, PI, PI2, _copysignINF, \
14 _float0, isnear0, isnear1, isneg0, \
15 _pos_self, _0_0, _1_0
16from pygeodesy.errors import CrossError, _IsnotError, VectorError, _xError
17from pygeodesy.fmath import euclid_, fdot, hypot_, hypot2_
18from pygeodesy.interns import NN, _coincident_, _colinear_, \
19 _COMMASPACE_, _xyz_
20from pygeodesy.lazily import _ALL_LAZY, _ALL_DOCS, _ALL_MODS as _MODS, \
21 _sys_version_info2
22from pygeodesy.named import _NamedBase, _NotImplemented, _xother3
23# from pygeodesy.namedTuples import Vector3Tuple # _MODS
24from pygeodesy.props import deprecated_method, Property, Property_RO, \
25 property_doc_, property_RO, _update_all
26from pygeodesy.streprs import Fmt, strs, unstr
27from pygeodesy.units import Float, Scalar
28# from pygeodesy.utily import sincos2 # _MODS
30from math import atan2, ceil, fabs, floor, trunc
32__all__ = _ALL_LAZY.vector3dBase
33__version__ = '24.03.06'
36class Vector3dBase(_NamedBase): # sync __methods__ with .fsums.Fsum
37 '''(INTERNAL) Generic 3-D vector base class.
38 '''
39 _crosserrors = True # un/set by .errors.crosserrors
41 _ll = None # original latlon, '_fromll'
42# _x = INT0 # X component
43# _y = INT0 # Y component
44# _z = INT0 # Z component
46 def __init__(self, x_xyz, y=INT0, z=INT0, ll=None, name=NN):
47 '''New L{Vector3d} or C{Vector3dBase} instance.
49 The vector may be normalised or use x, y, z for position and
50 distance from earth centre or height relative to the surface
51 of the earth' sphere or ellipsoid.
53 @arg x_xyz: X component of vector (C{scalar}) or a (3-D) vector
54 (C{Cartesian}, L{Ecef9Tuple}, C{Nvector}, L{Vector3d},
55 L{Vector3Tuple}, L{Vector4Tuple} or a C{tuple} or
56 C{list} of 3+ C{scalar} items).
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 ll: Optional latlon reference (C{LatLon}).
62 @kwarg name: Optional name (C{str}).
64 @raise VectorError: Invalid B{C{x_xyz}}.
65 '''
66 self._x, \
67 self._y, \
68 self._z = _xyz3(type(self), x_xyz, y, z) if isscalar(x_xyz) else \
69 _xyz3(type(self), x_xyz)
70 if ll:
71 self._ll = ll
72 if name:
73 self.name = name
75 def __abs__(self):
76 '''Return the norm of this vector.
78 @return: Norm, unit length (C{float});
79 '''
80 return self.length
82 def __add__(self, other):
83 '''Add this to an other vector (L{Vector3d}).
85 @return: Vectorial sum (L{Vector3d}).
87 @raise TypeError: Incompatible B{C{other}} C{type}.
88 '''
89 return self.plus(other)
91 def __bool__(self): # PYCHOK PyChecker
92 '''Is this vector non-zero?
93 '''
94 return bool(self.x or self.y or self.z)
96 def __ceil__(self): # PYCHOK no cover
97 '''Return a vector with the C{ceil} of these components.
99 @return: Ceil-ed (L{Vector3d}).
100 '''
101 return self._mapped(ceil)
103 def __cmp__(self, other): # Python 2-
104 '''Compare this and an other vector (L{Vector3d}).
106 @return: -1, 0 or +1 (C{int}).
108 @raise TypeError: Incompatible B{C{other}} C{type}.
109 '''
110 n = self.others(other).length
111 return -1 if self.length < n else (
112 +1 if self.length > n else 0)
114 cmp = __cmp__
116 def __divmod__(self, other): # PYCHOK no cover
117 '''Not implemented.'''
118 return _NotImplemented(self, other)
120 def __eq__(self, other):
121 '''Is this vector equal to an other vector?
123 @arg other: The other vector (L{Vector3d}).
125 @return: C{True} if equal, C{False} otherwise.
127 @raise TypeError: Incompatible B{C{other}} C{type}.
128 '''
129 return self.isequalTo(other, eps=EPS0)
131 def __float__(self): # PYCHOK no cover
132 '''Not implemented.'''
133 return _NotImplemented(self)
135 def __floor__(self): # PYCHOK no cover
136 '''Return a vector with the C{floor} of these components.
138 @return: Floor-ed (L{Vector3d}).
139 '''
140 return self._mapped(floor)
142 def __floordiv__(self, other): # PYCHOK no cover
143 '''Not implemented.'''
144 return _NotImplemented(self, other)
146 def __format__(self, *other): # PYCHOK no cover
147 '''Not implemented.'''
148 return _NotImplemented(self, *other)
150 def __ge__(self, other):
151 '''Is this vector longer than or equal to an other vector?
153 @arg other: The other vector (L{Vector3d}).
155 @return: C{True} if so, C{False} otherwise.
157 @raise TypeError: Incompatible B{C{other}} C{type}.
158 '''
159 return self.length >= self.others(other).length
161# def __getitem__(self, key):
162# '''Return C{item} at index or slice C{[B{key}]}.
163# '''
164# return self.xyz[key]
166 def __gt__(self, other):
167 '''Is this vector longer than an other vector?
169 @arg other: The other vector (L{Vector3d}).
171 @return: C{True} if so, C{False} otherwise.
173 @raise TypeError: Incompatible B{C{other}} C{type}.
174 '''
175 return self.length > self.others(other).length
177 def __hash__(self): # PYCHOK no cover
178 '''Return this instance' C{hash}.
179 '''
180 return hash(self.xyz) # XXX id(self)?
182 def __iadd__(self, other):
183 '''Add this and an other vector I{in-place}, C{this += B{other}}.
185 @arg other: The other vector (L{Vector3d}).
187 @raise TypeError: Incompatible B{C{other}} C{type}.
188 '''
189 return self._xyz(self.plus(other))
191 def __ifloordiv__(self, other): # PYCHOK no cover
192 '''Not implemented.'''
193 return _NotImplemented(self, other)
195 def __imatmul__(self, other): # PYCHOK Python 3.5+
196 '''Cross multiply this and an other vector I{in-place}, C{this @= B{other}}.
198 @arg other: The other vector (L{Vector3d}).
200 @raise TypeError: Incompatible B{C{other}} C{type}.
202 @see: Luciano Ramalho, "Fluent Python", O'Reilly, 2016 p. 397+, 2022 p. 578+.
203 '''
204 return self._xyz(self.cross(other))
206 def __imod__(self, other): # PYCHOK no cover
207 '''Not implemented.'''
208 return _NotImplemented(self, other)
210 def __imul__(self, scalar):
211 '''Multiply this vector by a scalar I{in-place}, C{this *= B{scalar}}.
213 @arg scalar: Factor (C{scalar}).
215 @raise TypeError: Non-scalar B{C{scalar}}.
216 '''
217 return self._xyz(self.times(scalar))
219 def __int__(self): # PYCHOK no cover
220 '''Return a vector with the C{int} of these components.
222 @return: Int-ed (L{Vector3d}).
223 '''
224 v = self.classof(_0_0)
225 v._x, v._y, v._z = map2(int, self.xyz)
226 return v
228 def __ipow__(self, other, *mod): # PYCHOK no cover
229 '''Not implemented.'''
230 return _NotImplemented(self, other, *mod)
232 def __isub__(self, other):
233 '''Subtract an other vector from this one I{in-place}, C{this -= B{other}}.
235 @arg other: The other vector (L{Vector3d}).
237 @raise TypeError: Incompatible B{C{other}} C{type}.
238 '''
239 return self._xyz(self.minus(other))
241# def __iter__(self):
242# '''Return an C{iter}ator over this vector's components.
243# '''
244# return iter(self.xyz)
246 def __itruediv__(self, scalar):
247 '''Divide this vector by a scalar I{in-place}, C{this /= B{scalar}}.
249 @arg scalar: The divisor (C{scalar}).
251 @raise TypeError: Non-scalar B{C{scalar}}.
252 '''
253 return self._xyz(self.dividedBy(scalar))
255 def __le__(self, other): # Python 3+
256 '''Is this vector shorter than or equal to an other vector?
258 @arg other: The other vector (L{Vector3d}).
260 @return: C{True} if so, C{False} otherwise.
262 @raise TypeError: Incompatible B{C{other}} C{type}.
263 '''
264 return self.length <= self.others(other).length
266# def __len__(self):
267# '''Return C{3}, always.
268# '''
269# return len(self.xyz)
271 def __lt__(self, other): # Python 3+
272 '''Is this vector shorter than an other vector?
274 @arg other: The other vector (L{Vector3d}).
276 @return: C{True} if so, C{False} otherwise.
278 @raise TypeError: Incompatible B{C{other}} C{type}.
279 '''
280 return self.length < self.others(other).length
282 def __matmul__(self, other): # PYCHOK Python 3.5+
283 '''Compute the cross product of this and an other vector, C{this @ B{other}}.
285 @arg other: The other vector (L{Vector3d}).
287 @return: Cross product (L{Vector3d}).
289 @raise TypeError: Incompatible B{C{other}} C{type}.
290 '''
291 return self.cross(other)
293 def __mod__(self, other): # PYCHOK no cover
294 '''Not implemented.'''
295 return _NotImplemented(self, other)
297 def __mul__(self, scalar):
298 '''Multiply this vector by a scalar, C{this * B{scalar}}.
300 @arg scalar: Factor (C{scalar}).
302 @return: Product (L{Vector3d}).
303 '''
304 return self.times(scalar)
306 def __ne__(self, other):
307 '''Is this vector not equal to an other vector?
309 @arg other: The other vector (L{Vector3d}).
311 @return: C{True} if so, C{False} otherwise.
313 @raise TypeError: Incompatible B{C{other}} C{type}.
314 '''
315 return not self.isequalTo(other, eps=EPS0)
317 def __neg__(self):
318 '''Return the opposite of this vector.
320 @return: This instance negated (L{Vector3d})
321 '''
322 return self.classof(-self.x, -self.y, -self.z)
324 def __pos__(self): # PYCHOK no cover
325 '''Return this vector I{as-is} or a copy.
327 @return: This instance (L{Vector3d})
328 '''
329 return self if _pos_self else self.copy()
331 def __pow__(self, other, *mod): # PYCHOK no cover
332 '''Not implemented.'''
333 return _NotImplemented(self, other, *mod)
335 __radd__ = __add__ # PYCHOK no cover
337 def __rdivmod__ (self, other): # PYCHOK no cover
338 '''Not implemented.'''
339 return _NotImplemented(self, other)
341# def __repr__(self):
342# '''Return the default C{repr(this)}.
343# '''
344# return self.toRepr()
346 def __rfloordiv__(self, other): # PYCHOK no cover
347 '''Not implemented.'''
348 return _NotImplemented(self, other)
350 def __rmatmul__(self, other): # PYCHOK Python 3.5+
351 '''Compute the cross product of an other and this vector, C{B{other} @ this}.
353 @arg other: The other vector (L{Vector3d}).
355 @return: Cross product (L{Vector3d}).
357 @raise TypeError: Incompatible B{C{other}} C{type}.
358 '''
359 return self.others(other).cross(self)
361 def __rmod__(self, other): # PYCHOK no cover
362 '''Not implemented.'''
363 return _NotImplemented(self, other)
365 __rmul__ = __mul__
367 def __round__(self, *ndigits): # PYCHOK no cover
368 '''Return a vector with these components C{rounded}.
370 @arg ndigits: Optional number of digits (C{int}).
372 @return: Rounded (L{Vector3d}).
373 '''
374 # <https://docs.Python.org/3.12/reference/datamodel.html?#object.__round__>
375 return self.classof(*(round(_, *ndigits) for _ in self.xyz))
377 def __rpow__(self, other, *mod): # PYCHOK no cover
378 '''Not implemented.'''
379 return _NotImplemented(self, other, *mod)
381 def __rsub__(self, other): # PYCHOK no cover
382 '''Subtract this vector from an other vector, C{B{other} - this}.
384 @arg other: The other vector (L{Vector3d}).
386 @return: Difference (L{Vector3d}).
388 @raise TypeError: Incompatible B{C{other}} C{type}.
389 '''
390 return self.others(other).minus(self)
392 def __rtruediv__(self, scalar): # PYCHOK no cover
393 '''Not implemented.'''
394 return _NotImplemented(self, scalar)
396# def __str__(self):
397# '''Return the default C{str(self)}.
398# '''
399# return self.toStr()
401 def __sub__(self, other):
402 '''Subtract an other vector from this vector, C{this - B{other}}.
404 @arg other: The other vector (L{Vector3d}).
406 @return: Difference (L{Vector3d}).
408 @raise TypeError: Incompatible B{C{other}} C{type}.
409 '''
410 return self.minus(other)
412 def __truediv__(self, scalar):
413 '''Divide this vector by a scalar, C{this / B{scalar}}.
415 @arg scalar: The divisor (C{scalar}).
417 @return: Quotient (L{Vector3d}).
419 @raise TypeError: Non-scalar B{C{scalar}}.
420 '''
421 return self.dividedBy(scalar)
423 def __trunc__(self): # PYCHOK no cover
424 '''Return a vector with the C{trunc} of these components.
426 @return: Trunc-ed (L{Vector3d}).
427 '''
428 return self._mapped(trunc)
430 if _sys_version_info2 < (3, 0): # PYCHOK no cover
431 # <https://docs.Python.org/2/library/operator.html#mapping-operators-to-functions>
432 __div__ = __truediv__
433 __idiv__ = __itruediv__
434 __long__ = __int__
435 __nonzero__ = __bool__
436 __rdiv__ = __rtruediv__
438 def angleTo(self, other, vSign=None, wrap=False):
439 '''Compute the angle between this and an other vector.
441 @arg other: The other vector (L{Vector3d}).
442 @kwarg vSign: Optional vector, if supplied (and out of the
443 plane of this and the other), angle is signed
444 positive if this->other is clockwise looking
445 along vSign or negative in opposite direction,
446 otherwise angle is unsigned.
447 @kwarg wrap: If C{True}, wrap/unroll the angle to +/-PI (C{bool}).
449 @return: Angle (C{radians}).
451 @raise TypeError: If B{C{other}} or B{C{vSign}} not a L{Vector3d}.
452 '''
453 x = self.cross(other)
454 s = x.length
455 # use vSign as reference to set sign of s
456 if s and vSign and x.dot(vSign) < 0:
457 s = -s
459 a = atan2(s, self.dot(other))
460 if wrap and fabs(a) > PI:
461 a -= _copysign(PI2, a)
462 return a
464 def apply(self, fun2, other_x, *y_z, **fun2_kwds):
465 '''Apply a 2-argument function pairwise to the components
466 of this and an other vector.
468 @arg fun2: 2-Argument callable (C{any(scalar, scalar}),
469 return a C{scalar} or L{INT0} result.
470 @arg other_x: Other X component (C{scalar}) or a vector
471 with X, Y and Z components (C{Cartesian},
472 L{Ecef9Tuple}, C{Nvector}, L{Vector3d},
473 L{Vector3Tuple} or L{Vector4Tuple}).
474 @arg y_z: Other Y and Z components, positional (C{scalar}, C{scalar}).
475 @kwarg fun2_kwds: Optional keyword arguments for B{C{fun2}}.
477 @return: New, applied vector (L{Vector3d}).
479 @raise ValueError: Invalid B{C{other_x}} or B{C{y_z}}.
480 '''
481 if not callable(fun2):
482 raise _IsnotError(callable.__name__, fun2=fun2)
484 if fun2_kwds:
485 def _f2(a, b):
486 return fun2(a, b, **fun2_kwds)
487 else:
488 _f2 = fun2
490 xyz = _xyz3(self.apply, other_x, *y_z)
491 xyz = (_f2(a, b) for a, b in _zip(self.xyz, xyz)) # strict=True
492 return self.classof(*xyz)
494 def cross(self, other, raiser=None, eps0=EPS): # raiser=NN
495 '''Compute the cross product of this and an other vector.
497 @arg other: The other vector (L{Vector3d}).
498 @kwarg raiser: Optional, L{CrossError} label if raised (C{str},
499 non-L{NN}).
500 @kwarg eps0: Near-zero tolerance (C{scalar}), same units as
501 C{x}, C{y}, and C{z}.
503 @return: Cross product (L{Vector3d}).
505 @raise CrossError: Zero or near-zero cross product and both
506 B{C{raiser}} and L{pygeodesy.crosserrors} set.
508 @raise TypeError: Incompatible B{C{other}} C{type}.
509 '''
510 X, Y, Z = self.others(other).xyz
511 x, y, z = self.xyz
512 xyz = ((y * Z - Y * z),
513 (z * X - Z * x),
514 (x * Y - X * y))
516 if raiser and self.crosserrors and eps0 > 0 \
517 and max(map(fabs, xyz)) < eps0:
518 r = other._fromll or other
519 s = self._fromll or self
520 t = self.isequalTo(other, eps=eps0)
521 t = _coincident_ if t else _colinear_
522 raise CrossError(raiser, s, other=r, txt=t)
524 return self.classof(*xyz)
526 @property_doc_('''raise or ignore L{CrossError} exceptions (C{bool}).''')
527 def crosserrors(self):
528 '''Get L{CrossError} exceptions (C{bool}).
529 '''
530 return self._crosserrors
532 @crosserrors.setter # PYCHOK setter!
533 def crosserrors(self, raiser):
534 '''Raise or ignore L{CrossError} exceptions (C{bool}).
535 '''
536 self._crosserrors = bool(raiser)
538 def dividedBy(self, divisor):
539 '''Divide this vector by a scalar.
541 @arg divisor: The divisor (C{scalar}).
543 @return: New, scaled vector (L{Vector3d}).
545 @raise TypeError: Non-scalar B{C{divisor}}.
547 @raise VectorError: Invalid or zero B{C{divisor}}.
548 '''
549 d = Scalar(divisor=divisor)
550 try:
551 return self._times(_1_0 / d)
552 except (ValueError, ZeroDivisionError) as x:
553 raise VectorError(divisor=divisor, cause=x)
555 def dot(self, other):
556 '''Compute the dot (scalar) product of this and an other vector.
558 @arg other: The other vector (L{Vector3d}).
560 @return: Dot product (C{float}).
562 @raise TypeError: Incompatible B{C{other}} C{type}.
563 '''
564 return self.length2 if other is self else \
565 fdot(self.xyz, *self.others(other).xyz)
567 @deprecated_method
568 def equals(self, other, units=False): # PYCHOK no cover
569 '''DEPRECATED, use method C{isequalTo}.
570 '''
571 return self.isequalTo(other, units=units)
573 @Property_RO
574 def euclid(self):
575 '''I{Approximate} the length (norm, magnitude) of this vector (C{Float}).
577 @see: Properties C{length} and C{length2} and function
578 L{pygeodesy.euclid_}.
579 '''
580 return Float(euclid=euclid_(self.x, self.y, self.z))
582 def equirectangular(self, other):
583 '''I{Approximate} the different between this and an other vector.
585 @arg other: Vector to subtract (C{Vector3dBase}).
587 @return: The lenght I{squared} of the difference (C{Float}).
589 @raise TypeError: Incompatible B{C{other}} C{type}.
591 @see: Property C{length2}.
592 '''
593 d = self.minus(other)
594 return Float(equirectangular=hypot2_(d.x, d.y, d.z))
596 @Property
597 def _fromll(self):
598 '''(INTERNAL) Get the latlon reference (C{LatLon}) or C{None}.
599 '''
600 return self._ll
602 @_fromll.setter # PYCHOK setter!
603 def _fromll(self, ll):
604 '''(INTERNAL) Set the latlon reference (C{LatLon}) or C{None}.
605 '''
606 self._ll = ll or None
608 @property_RO
609 def homogeneous(self):
610 '''Get this vector's homogeneous representation (L{Vector3d}).
611 '''
612 x, y, z = self.xyz
613 if z:
614 x = x / z # /= chokes PyChecker
615 y = y / z
616# z = _1_0
617 else:
618 if isneg0(z):
619 x = -x
620 y = -y
621 x = _copysignINF(x)
622 y = _copysignINF(y)
623# z = NAN
624 return self.classof(x, y, _1_0)
626 def intermediateTo(self, other, fraction, **unused): # height=None, wrap=False
627 '''Locate the vector at a given fraction between (or along) this
628 and an other vector.
630 @arg other: The other vector (L{Vector3d}).
631 @arg fraction: Fraction between both vectors (C{scalar},
632 0.0 for this and 1.0 for the other vector).
634 @return: Intermediate vector (L{Vector3d}).
636 @raise TypeError: Incompatible B{C{other}} C{type}.
637 '''
638 f = Scalar(fraction=fraction)
639 if isnear0(f): # PYCHOK no cover
640 r = self
641 else:
642 r = self.others(other)
643 if not isnear1(f): # self * (1 - f) + r * f
644 r = self.plus(r.minus(self)._times(f))
645 return r
647 def isconjugateTo(self, other, minum=1, eps=EPS):
648 '''Determine whether this and an other vector are conjugates.
650 @arg other: The other vector (C{Cartesian}, L{Ecef9Tuple},
651 L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}).
652 @kwarg minum: Minimal number of conjugates required (C{int}, 0..3).
653 @kwarg eps: Tolerance for equality and conjugation (C{scalar}),
654 same units as C{x}, C{y}, and C{z}.
656 @return: C{True} if both vector's components either match
657 or at least C{B{minum}} have opposite signs.
659 @raise TypeError: Incompatible B{C{other}} C{type}.
661 @see: Method C{isequalTo}.
662 '''
663 self.others(other)
664 n = 0
665 for a, b in zip(self.xyz, other.xyz):
666 if fabs(a + b) < eps and ((a < 0 and b > 0) or
667 (a > 0 and b < 0)):
668 n += 1 # conjugate
669 elif fabs(a - b) > eps:
670 return False # unequal
671 return bool(n >= minum)
673 def isequalTo(self, other, units=False, eps=EPS):
674 '''Check if this and an other vector are equal or equivalent.
676 @arg other: The other vector (L{Vector3d}).
677 @kwarg units: Optionally, compare the normalized, unit
678 version of both vectors.
679 @kwarg eps: Tolerance for equality (C{scalar}), same units as
680 C{x}, C{y}, and C{z}.
682 @return: C{True} if vectors are identical, C{False} otherwise.
684 @raise TypeError: Incompatible B{C{other}} C{type}.
686 @see: Method C{isconjugateTo}.
687 '''
688 if units:
689 self.others(other)
690 d = self.unit().minus(other.unit())
691 else:
692 d = self.minus(other)
693 return max(map(fabs, d.xyz)) < eps
695 @Property_RO
696 def length(self): # __dict__ value overwritten by Property_RO C{_united}
697 '''Get the length (norm, magnitude) of this vector (C{Float}).
699 @see: Properties L{length2} and L{euclid}.
700 '''
701 return Float(length=hypot_(self.x, self.y, self.z))
703 @Property_RO
704 def length2(self): # __dict__ value overwritten by Property_RO C{_united}
705 '''Get the length I{squared} of this vector (C{Float}).
707 @see: Property L{length} and method C{equirectangular}.
708 '''
709 return Float(length2=hypot2_(self.x, self.y, self.z))
711 def _mapped(self, func):
712 '''(INTERNAL) Map these components.
713 '''
714 return self.classof(*map2(func, self.xyz))
716 def minus(self, other):
717 '''Subtract an other vector from this vector.
719 @arg other: The other vector (L{Vector3d}).
721 @return: New vector difference (L{Vector3d}).
723 @raise TypeError: Incompatible B{C{other}} C{type}.
724 '''
725 xyz = self.others(other).xyz
726 return self._minus(*xyz)
728 def _minus(self, x, y, z):
729 '''(INTERNAL) Helper for methods C{.minus} and C{.minus_}.
730 '''
731 return self.classof(self.x - x, self.y - y, self.z - z)
733 def minus_(self, other_x, *y_z):
734 '''Subtract separate X, Y and Z components from this vector.
736 @arg other_x: X component (C{scalar}) or a vector's
737 X, Y, and Z components (C{Cartesian},
738 L{Ecef9Tuple}, C{Nvector}, L{Vector3d},
739 L{Vector3Tuple}, L{Vector4Tuple}).
740 @arg y_z: Y and Z components (C{scalar}, C{scalar}),
741 ignored if B{C{other_x}} is not C{scalar}.
743 @return: New, vectiorial vector (L{Vector3d}).
745 @raise ValueError: Invalid B{C{other_x}} or B{C{y_z}}.
746 '''
747 return self._minus(*_xyz3(self.minus_, other_x, *y_z))
749 def negate(self):
750 '''Return this vector in opposite direction.
752 @return: New, opposite vector (L{Vector3d}).
753 '''
754 return self.classof(-self.x, -self.y, -self.z)
756 __neg__ = negate # PYCHOK no cover
758 @Property_RO
759 def _N_vector(self):
760 '''(INTERNAL) Get the (C{nvectorBase._N_vector_})
761 '''
762 return _MODS.nvectorBase._N_vector_(*self.xyz, name=self.name)
764 def others(self, *other, **name_other_up):
765 '''Refined class comparison.
767 @arg other: The other vector (L{Vector3d}).
768 @kwarg name_other_up: Overriding C{name=other} and C{up=1}
769 keyword arguments.
771 @return: The B{C{other}} if compatible.
773 @raise TypeError: Incompatible B{C{other}} C{type}.
774 '''
775 other, name, up = _xother3(self, other, **name_other_up)
776 if not isinstance(other, Vector3dBase):
777 _NamedBase.others(self, other, name=name, up=up + 1)
778 return other
780 def plus(self, other):
781 '''Add this vector and an other vector.
783 @arg other: The other vector (L{Vector3d}).
785 @return: Vectorial sum (L{Vector3d}).
787 @raise TypeError: Incompatible B{C{other}} C{type}.
788 '''
789 xyz = self.others(other).xyz
790 return self._plus(*xyz)
792 sum = plus # alternate name
794 def _plus(self, x, y, z):
795 '''(INTERNAL) Helper for methods C{.plus} and C{.plus_}.
796 '''
797 return self.classof(self.x + x, self.y + y, self.z + z)
799 def plus_(self, other_x, *y_z):
800 '''Sum of this vector and separate X, Y and Z components.
802 @arg other_x: X component (C{scalar}) or a vector's
803 X, Y, and Z components (C{Cartesian},
804 L{Ecef9Tuple}, C{Nvector}, L{Vector3d},
805 L{Vector3Tuple}, L{Vector4Tuple}).
806 @arg y_z: Y and Z components (C{scalar}, C{scalar}),
807 ignored if B{C{other_x}} is not C{scalar}.
809 @return: New, vectiorial vector (L{Vector3d}).
811 @raise ValueError: Invalid B{C{other_x}} or B{C{y_z}}.
812 '''
813 return self._plus(*_xyz3(self.plus_, other_x, *y_z))
815 def rotate(self, axis, theta):
816 '''Rotate this vector around an axis by a specified angle.
818 @arg axis: The axis being rotated around (L{Vector3d}).
819 @arg theta: The angle of rotation (C{radians}).
821 @return: New, rotated vector (L{Vector3d}).
823 @see: U{Rotation matrix from axis and angle<https://WikiPedia.org/wiki/
824 Rotation_matrix#Rotation_matrix_from_axis_and_angle>} and
825 U{Quaternion-derived rotation matrix<https://WikiPedia.org/wiki/
826 Quaternions_and_spatial_rotation#Quaternion-derived_rotation_matrix>}.
827 '''
828 s, c = _MODS.utily.sincos2(theta) # rotation angle
829 d = _1_0 - c
830 if d or s:
831 p = self.unit().xyz # point being rotated
832 r = self.others(axis=axis).unit() # axis being rotated around
834 ax, ay, az = r.xyz # quaternion-derived rotation matrix
835 bx, by, bz = r.times(d).xyz
836 sx, sy, sz = r.times(s).xyz
838 x = fdot(p, ax * bx + c, ax * by - sz, ax * bz + sy)
839 y = fdot(p, ay * bx + sz, ay * by + c, ay * bz - sx)
840 z = fdot(p, az * bx - sy, az * by + sx, az * bz + c)
841 else: # unrotated
842 x, y, z = self.xyz
843 return self.classof(x, y, z)
845 @deprecated_method
846 def rotateAround(self, axis, theta): # PYCHOK no cover
847 '''DEPRECATED, use method C{rotate}.'''
848 return self.rotate(axis, theta)
850 def times(self, factor):
851 '''Multiply this vector by a scalar.
853 @arg factor: Scale factor (C{scalar}).
855 @return: New, scaled vector (L{Vector3d}).
857 @raise TypeError: Non-scalar B{C{factor}}.
858 '''
859 return self._times(Scalar(factor=factor))
861 def _times(self, s):
862 '''(INTERNAL) Helper for C{.dividedBy} and C{.times}.
863 '''
864 return self.classof(self.x * s, self.y * s, self.z * s)
866 def times_(self, other_x, *y_z):
867 '''Multiply this vector's components by separate X, Y and Z factors.
869 @arg other_x: X scale factor (C{scalar}) or a vector's
870 X, Y, and Z components as scale factors
871 (C{Cartesian}, L{Ecef9Tuple}, C{Nvector},
872 L{Vector3d}, L{Vector3Tuple}, L{Vector4Tuple}).
873 @arg y_z: Y and Z scale factors (C{scalar}, C{scalar}),
874 ignored if B{C{other_x}} is not C{scalar}.
876 @return: New, scaled vector (L{Vector3d}).
878 @raise ValueError: Invalid B{C{other_x}} or B{C{y_z}}.
879 '''
880 x, y, z = _xyz3(self.times_, other_x, *y_z)
881 return self.classof(self.x * x, self.y * y, self.z * z)
883# @deprecated_method
884# def to2ab(self): # PYCHOK no cover
885# '''DEPRECATED, use property C{Nvector.philam}.
886#
887# @return: A L{PhiLam2Tuple}C{(phi, lam)}.
888# '''
889# return _MODS.formy.n_xyz2philam(self.x, self.y, self.z)
891# @deprecated_method
892# def to2ll(self): # PYCHOK no cover
893# '''DEPRECATED, use property C{Nvector.latlon}.
894#
895# @return: A L{LatLon2Tuple}C{(lat, lon)}.
896# '''
897# return _MODS.formy.n_xyz2latlon(self.x, self.y, self.z)
899 @deprecated_method
900 def to3xyz(self): # PYCHOK no cover
901 '''DEPRECATED, use property L{xyz}.
902 '''
903 return self.xyz
905 def toStr(self, prec=5, fmt=Fmt.PAREN, sep=_COMMASPACE_): # PYCHOK expected
906 '''Return a string representation of this vector.
908 @kwarg prec: Number of decimal places (C{int}).
909 @kwarg fmt: Enclosing format to use (C{str}).
910 @kwarg sep: Separator between components (C{str}).
912 @return: Vector as "(x, y, z)" (C{str}).
913 '''
914 t = sep.join(strs(self.xyz, prec=prec))
915 return (fmt % (t,)) if fmt else t
917 def unit(self, ll=None):
918 '''Normalize this vector to unit length.
920 @kwarg ll: Optional, original location (C{LatLon}).
922 @return: Normalized vector (L{Vector3d}).
923 '''
924 u = self._united
925 if ll:
926 u._fromll = ll
927 return u
929 @Property_RO
930 def _united(self): # __dict__ value overwritten below
931 '''(INTERNAL) Get normalized vector (L{Vector3d}).
932 '''
933 n = self.length
934 if n > EPS0 and fabs(n - _1_0) > EPS0:
935 u = self._xnamed(self.dividedBy(n))
936 u._update(False, length=_1_0, length2=_1_0, _united=u)
937 else:
938 u = self.copy()
939 u._update(False, _united=u)
940 if self._fromll:
941 u._fromll = self._fromll
942 return u
944 @Property
945 def x(self):
946 '''Get the X component (C{float}).
947 '''
948 return self._x
950 @x.setter # PYCHOK setter!
951 def x(self, x):
952 '''Set the X component, if different (C{float}).
953 '''
954 x = Float(x=x)
955 if self._x != x:
956 _update_all(self, needed=3)
957 self._x = x
959 @Property
960 def xyz(self):
961 '''Get the X, Y and Z components (L{Vector3Tuple}C{(x, y, z)}).
962 '''
963 return _MODS.namedTuples.Vector3Tuple(self.x, self.y, self.z, name=self.name)
965 @xyz.setter # PYCHOK setter!
966 def xyz(self, xyz):
967 '''Set the X, Y and Z components (C{Cartesian}, L{Ecef9Tuple},
968 C{Nvector}, L{Vector3d}, L{Vector3Tuple}, L{Vector4Tuple}
969 or a C{tuple} or C{list} of 3+ C{scalar} items).
970 '''
971 self._xyz(xyz)
973 def _xyz(self, x_xyz, *y_z):
974 '''(INTERNAL) Set the C{_x}, C{_y} and C{_z} attributes.
975 '''
976 _update_all(self, needed=3)
977 self._x, self._y, self._z = _xyz3(_xyz_, x_xyz, *y_z)
978 return self
980 @property_RO
981 def x2y2z2(self):
982 '''Get the X, Y and Z components I{squared} (3-tuple C{(x**2, y**2, z**2)}).
983 '''
984 return self.x**2, self.y**2, self.z**2
986 @Property
987 def y(self):
988 '''Get the Y component (C{float}).
989 '''
990 return self._y
992 @y.setter # PYCHOK setter!
993 def y(self, y):
994 '''Set the Y component, if different (C{float}).
995 '''
996 y = Float(y=y)
997 if self._y != y:
998 _update_all(self, needed=3)
999 self._y = y
1001 @Property
1002 def z(self):
1003 '''Get the Z component (C{float}).
1004 '''
1005 return self._z
1007 @z.setter # PYCHOK setter!
1008 def z(self, z):
1009 '''Set the Z component, if different (C{float}).
1010 '''
1011 z = Float(z=z)
1012 if self._z != z:
1013 _update_all(self, needed=3)
1014 self._z = z
1017def _xyz3(where, x_xyz, *y_z): # in .cartesianBase._rtp3
1018 '''(INTERNAL) Helper for C{Vector3dBase.__init__}, C{-.apply}, C{-.times_} and C{-._xyz}.
1019 '''
1020 try:
1021 x_y_z = map1(_float0, x_xyz, *y_z) if y_z else ( # islistuple for VectorXTuple
1022 map2(_float0, x_xyz[:3]) if islistuple(x_xyz, minum=3) else
1023 x_xyz.xyz)
1024 except (AttributeError, TypeError, ValueError) as x:
1025 raise _xError(x, unstr(where, x_xyz, *y_z))
1026 return x_y_z
1029__all__ += _ALL_DOCS(Vector3dBase)
1031# **) MIT License
1032#
1033# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
1034#
1035# Permission is hereby granted, free of charge, to any person obtaining a
1036# copy of this software and associated documentation files (the "Software"),
1037# to deal in the Software without restriction, including without limitation
1038# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1039# and/or sell copies of the Software, and to permit persons to whom the
1040# Software is furnished to do so, subject to the following conditions:
1041#
1042# The above copyright notice and this permission notice shall be included
1043# in all copies or substantial portions of the Software.
1044#
1045# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1046# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1047# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1048# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1049# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1050# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1051# OTHER DEALINGS IN THE SOFTWARE.