# Coverage for pygeodesy/vector3d.py : 94%

## 374 statements 353 run 21 missing 34 excluded

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 | # -*- coding: utf-8 -*- u'''Generic 3-D vector base class L{Vector3d}, class L{VectorError} and functions L{intersections2}, L{iscolinearWith}, L{nearestOn}, L{parse3d}, L{sumOf} and L{trilaterate3d2}. Pure Python implementation of vector-based functions by I{(C) Chris Veness 2011-2015} published under the same MIT Licence**, see U{Vector-based geodesy <https://www.Movable-Type.co.UK/scripts/latlong-vectors.html>}. @newfield example: Example, Examples ''' from pygeodesy.basics import isscalar, len2, map1, neg, property_doc_, \ property_RO, _xnumpy from pygeodesy.errors import _AssertionError, CrossError, IntersectionError, \ _IsnotError, _TypeError, _ValueError, _xkwds, \ _xkwds_popitem from pygeodesy.fmath import euclid_, fdot, fsum, fsum_, hypot_, hypot2_ from pygeodesy.formy import n_xyz2latlon, n_xyz2philam, _radical2 from pygeodesy.interns import EPS, EPS1, MISSING, NN, PI, PI2, _coincident_, \ _colinear_, _COMMA_, _COMMASPACE_, _datum_, _h_, \ _height_, _invalid_, _intersection_, _name_, \ _near_concentric_, _no_, _scalar_, _SPACE_, \ _too_, _y_, _z_, _0_0, _1_0 from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY from pygeodesy.named import modulename, _NamedBase, _xnamed, _xother3, _xotherError from pygeodesy.namedTuples import Vector3Tuple # Vector4Tuple from pygeodesy.streprs import Fmt, strs from pygeodesy.units import Radius, Radius_ from math import atan2, copysign, cos, sin, sqrt __all__ = _ALL_LAZY.vector3d __version__ = '20.11.04' def _xyzn4(xyz, y, z, Error=_TypeError): # imported by .ecef '''(INTERNAL) Get an C{(x, y, z, name)} 4-tuple. ''' try: t = xyz.x, xyz.y, xyz.z except AttributeError: t = xyz, y, z try: x, y, z = map1(float, *t) except (TypeError, ValueError) as x: d = dict(zip(('xyz', _y_, _z_), t)) raise Error(txt=str(x), **d) return x, y, z, getattr(xyz, _name_, NN) def _xyzhdn6(xyz, y, z, height, datum, ll, Error=_TypeError): # by .cartesianBase, .nvectorBase '''(INTERNAL) Get an C{(x, y, z, h, d, name)} 6-tuple. ''' x, y, z, n = _xyzn4(xyz, y, z, Error=Error) h = height or getattr(xyz, _height_, None) \ or getattr(xyz, _h_, None) \ or getattr(ll, _height_, None) d = datum or getattr(xyz, _datum_, None) \ or getattr(ll, _datum_, None) return x, y, z, h, d, n class VectorError(_ValueError): '''L{Vector3d} or C{*Nvector} issue. ''' pass class Vector3d(_NamedBase): # XXX or _NamedTuple or Vector3Tuple? '''Generic 3-D vector manipulation. In a geodesy context, these may be used to represent: - n-vector representing a normal to point on earth's surface - earth-centered, earth-fixed vector (= n-vector for spherical model) - great circle normal to vector - motion vector on earth's surface - etc. ''' _crosserrors = True # un/set by .errors.crosserrors _fromll = None # original latlon, '_fromll' _length = None # cached length _length2 = None # cached length2 _numpy = None # module numpy iff imported by trilaterate3d2 below _united = None # cached norm, unit (L{Vector3d}) _xyz = None # cached xyz (L{Vector3Tuple}) _x = 0 # X component _y = 0 # Y component _z = 0 # Z component def __init__(self, x, y, z, ll=None, name=NN): '''New 3-D L{Vector3d}. The vector may be normalised or use x/y/z values for height relative to the surface of the sphere or ellipsoid, distance from earth centre, etc. @arg x: X component of vector (C{scalar}). @arg y: Y component of vector (C{scalar}). @arg z: Z component of vector (C{scalar}). @kwarg ll: Optional latlon reference (C{LatLon}). @kwarg name: Optional name (C{str}). ''' self._x = x self._y = y self._z = z if ll: self._fromll = ll if name: self.name = name def __abs__(self): '''Return the norm of this vector. @return: Norm, unit length (C{float}); ''' return self.length def __add__(self, other): '''Add this to an other vector (L{Vector3d}). @return: Vectorial sum (L{Vector3d}). @raise TypeError: Incompatible B{C{other}} C{type}. ''' return self.plus(other) # __iadd__ = __add__ __radd__ = __add__ def __cmp__(self, other): # Python 2- '''Compare this and an other vector @arg other: The other vector (L{Vector3d}). @return: -1, 0 or +1 (C{int}). @raise TypeError: Incompatible B{C{other}} C{type}. ''' self.others(other) return -1 if self.length < other.length else ( +1 if self.length > other.length else 0) cmp = __cmp__ def __div__(self, scalar): '''Divide this vector by a scalar. @arg scalar: The divisor (C{scalar}). @return: Quotient (L{Vector3d}). @raise TypeError: Non-scalar B{C{scalar}}. ''' return self.dividedBy(scalar) # __itruediv__ = __div__ __truediv__ = __div__ def __eq__(self, other): '''Is this vector equal to an other vector? @arg other: The other vector (L{Vector3d}). @return: C{True} if equal, C{False} otherwise. @raise TypeError: Incompatible B{C{other}} C{type}. ''' self.others(other) return self.isequalTo(other) def __ge__(self, other): '''Is this vector longer than or equal to an other vector? @arg other: The other vector (L{Vector3d}). @return: C{True} if so, C{False} otherwise. @raise TypeError: Incompatible B{C{other}} C{type}. ''' self.others(other) return self.length >= other.length def __gt__(self, other): '''Is this vector longer than an other vector? @arg other: The other vector (L{Vector3d}). @return: C{True} if so, C{False} otherwise. @raise TypeError: Incompatible B{C{other}} C{type}. ''' self.others(other) return self.length > other.length def __le__(self, other): # Python 3+ '''Is this vector shorter than or equal to an other vector? @arg other: The other vector (L{Vector3d}). @return: C{True} if so, C{False} otherwise. @raise TypeError: Incompatible B{C{other}} C{type}. ''' self.others(other) return self.length <= other.length def __lt__(self, other): # Python 3+ '''Is this vector shorter than an other vector? @arg other: The other vector (L{Vector3d}). @return: C{True} if so, C{False} otherwise. @raise TypeError: Incompatible B{C{other}} C{type}. ''' self.others(other) return self.length < other.length # Luciano Ramalho, "Fluent Python", page 397, O'Reilly 2016 def __matmul__(self, other): # PYCHOK Python 3.5+ ... c = a @ b '''Compute the cross product of this and an other vector. @arg other: The other vector (L{Vector3d}). @return: Cross product (L{Vector3d}). @raise TypeError: Incompatible B{C{other}} C{type}. ''' return self.cross(other) # __imatmul__ = __matmul__ def __mul__(self, scalar): '''Multiply this vector by a scalar @arg scalar: Factor (C{scalar}). @return: Product (L{Vector3d}). ''' return self.times(scalar) # __imul__ = __mul__ # __rmul__ = __mul__ def __ne__(self, other): '''Is this vector not equal to an other vector? @arg other: The other vector (L{Vector3d}). @return: C{True} if so, C{False} otherwise. @raise TypeError: Incompatible B{C{other}} C{type}. ''' self.others(other) return not self.isequalTo(other) def __neg__(self): '''Negate this vector. @return: Negative (L{Vector3d}) ''' return self.negate() def __pos__(self): '''Copy this vector. @return: Positive (L{Vector3d}) ''' return self.copy() # Luciano Ramalho, "Fluent Python", page 397, O'Reilly 2016 def __rmatmul__(self, other): # PYCHOK Python 3.5+ ... c = a @ b '''Compute the cross product of an other and this vector. @arg other: The other vector (L{Vector3d}). @return: Cross product (L{Vector3d}). @raise TypeError: Incompatible B{C{other}} C{type}. ''' self.others(other) return other.cross(self) def __rsub__(self, other): '''Subtract this vector from an other vector. @arg other: The other vector (L{Vector3d}). @return: Difference (L{Vector3d}). @raise TypeError: Incompatible B{C{other}} C{type}. ''' self.others(other) return other.minus(self) def __sub__(self, other): '''Subtract an other vector from this vector. @arg other: The other vector (L{Vector3d}). @return: Difference (L{Vector3d}). @raise TypeError: Incompatible B{C{other}} C{type}. ''' return self.minus(other) # __isub__ = __sub__ def _update(self, updated, *attrs): '''(INTERNAL) Zap cached attributes if updated. ''' if updated: _NamedBase._update(self, updated, # '_fromll' '_length', '_length2', '_united', '_xyz', *attrs) def angleTo(self, other, vSign=None, wrap=False): '''Compute the angle between this and an other vector. @arg other: The other vector (L{Vector3d}). @kwarg vSign: Optional vector, if supplied (and out of the plane of this and the other), angle is signed positive if this->other is clockwise looking along vSign or negative in opposite direction, otherwise angle is unsigned. @kwarg warp: Wrap/unroll the angle to +/-PI (c{bool}). @return: Angle (C{radians}). @raise TypeError: If B{C{other}} or B{C{vSign}} not a L{Vector3d}. ''' x = self.cross(other) s = x.length if s < EPS: return _0_0 # use vSign as reference to get sign of s if vSign and x.dot(vSign) < 0: s = neg(s) a = atan2(s, self.dot(other)) if wrap and abs(a) > PI: a -= copysign(PI2, a) return a def cross(self, other, raiser=None): # raiser=NN '''Compute the cross product of this and an other vector. @arg other: The other vector (L{Vector3d}). @kwarg raiser: Optional, L{CrossError} label if raised (C{str}). @return: Cross product (L{Vector3d}). @raise CrossError: Zero or near-zero cross product and both B{C{raiser}} and L{crosserrors} set. @raise TypeError: Incompatible B{C{other}} C{type}. ''' self.others(other) x = self.y * other.z - self.z * other.y y = self.z * other.x - self.x * other.z z = self.x * other.y - self.y * other.x if raiser and self.crosserrors and max(map1(abs, x, y, z)) < EPS: t = _coincident_ if self.isequalTo(other) else _colinear_ r = getattr(other, '_fromll', None) or other raise CrossError(raiser, r, txt=t) return self.classof(x, y, z) @property_doc_('''raise or ignore L{CrossError} exceptions (C{bool}).''') def crosserrors(self): '''Get L{CrossError} exceptions (C{bool}). ''' return self._crosserrors @crosserrors.setter # PYCHOK setter! def crosserrors(self, raiser): '''Raise L{CrossError} exceptions (C{bool}). ''' self._crosserrors = bool(raiser) def dividedBy(self, factor): '''Divide this vector by a scalar. @arg factor: The divisor (C{scalar}). @return: New, scaled vector (L{Vector3d}). @raise TypeError: Non-scalar B{C{factor}}. @raise VectorError: Invalid or zero B{C{factor}}. ''' if not isscalar(factor): raise _IsnotError(_scalar_, factor=factor) try: return self.times(_1_0 / factor) except (ValueError, ZeroDivisionError) as x: raise VectorError(factor=factor, txt=str(x)) def dot(self, other): '''Compute the dot (scalar) product of this and an other vector. @arg other: The other vector (L{Vector3d}). @return: Dot product (C{float}). @raise TypeError: Incompatible B{C{other}} C{type}. ''' if other is self: d = self.length2 else: self.others(other) d = fdot(self.xyz, *other.xyz) return d def equals(self, other, units=False): # PYCHOK no cover '''DEPRECATED, use method C{isequalTo}. ''' return self.isequalTo(other, units=units) @property_RO def euclid(self): '''Approximate the length (norm, magnitude) of this vector. @see: Function L{euclid_} and properties C{length} and C{length2}. ''' return euclid_(self.x, self.y, self.z) def iscolinearWith(self, point1, point2, eps=EPS): '''Check whether this and two other points are colinear. @arg point1: One point (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}). @arg point2: Another point (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}). @kwarg eps: Tolerance (C{scalar}), same units as C{x}, C{y}, and C{z}. @return: C{True} if colinear, C{False} otherwise. @raise TypeError: Invalid B{C{point1}} or B{C{point2}}. @see: Method L{nearestOn}. ''' v = self if self.name else _otherV3d(this=self) return _iscolinearWith(v, point1, point2, eps=eps) def isequalTo(self, other, units=False, eps=EPS): '''Check if this and an other vector are equal or equivalent. @arg other: The other vector (L{Vector3d}). @kwarg units: Optionally, compare the normalized, unit version of both vectors. @kwarg eps: Tolerance (C{scalar}), same units as C{x}, C{y}, and C{z}. @return: C{True} if vectors are identical, C{False} otherwise. @raise TypeError: Incompatible B{C{other}} C{type}. @example: >>> v1 = Vector3d(52.205, 0.119) >>> v2 = Vector3d(52.205, 0.119) >>> e = v1.isequalTo(v2) # True ''' self.others(other) if units: d = self.unit().minus(other.unit()) else: d = self.minus(other) return max(map(abs, d.xyz)) < eps @property_RO def length(self): '''Get the length (norm, magnitude) of this vector (C{float}). @see: Properties C{length2} and C{euclid}. ''' if self._length is None: self._length = hypot_(self.x, self.y, self.z) return self._length @property_RO def length2(self): '''Get the length I{squared} of this vector (C{float}). @see: Property C{length}. ''' if self._length2 is None: self._length2 = hypot2_(self.x, self.y, self.z) return self._length2 def minus(self, other): '''Subtract an other vector from this vector. @arg other: The other vector (L{Vector3d}). @return: New vector difference (L{Vector3d}). @raise TypeError: Incompatible B{C{other}} C{type}. ''' self.others(other) return self.classof(self.x - other.x, self.y - other.y, self.z - other.z) def nearestOn(self, other1, other2, within=True): '''Locate the point between two points closest to this point. @arg other1: Start point (L{Vector3d}). @arg other2: End point (L{Vector3d}). @kwarg within: If C{True} return the closest point between the given points, otherwise the closest point on the extended line through both points (C{bool}). @return: Closest point (L{Vector3d}). @raise TypeError: If B{C{other1}} or B{C{other2}} is not L{Vector3d}. @see: Method L{sphericalTrigonometry.LatLon.nearestOn3} and U{3-D Point-Line distance<https://MathWorld.Wolfram.com/ Point-LineDistance3-Dimensional.html>}. ''' return _nearestOn(self, _V3d(other1) or _otherV3d(other1=other1), _V3d(other2) or _otherV3d(other2=other2), within=within) def negate(self): '''Return this vector in opposite direction. @return: New, opposite vector (L{Vector3d}). ''' return self.classof(-self.x, -self.y, -self.z) @property_RO def _N_vector(self): '''(INTERNAL) Get the (C{nvectorBase._N_vector_}) ''' from pygeodesy.nvectorBase import _N_vector_ return _N_vector_(*(self._xyz or self.xyz)) def others(self, *other, **name_other_up): '''Refined class comparison. @arg other: The other vector (L{Vector3d}). @kwarg name_other_up: Overriding C{name=other} and C{up=1} keyword arguments. @return: The B{C{other}} if compatible. @raise TypeError: Incompatible B{C{other}} C{type}. ''' other, name, up = _xother3(self, other, **name_other_up) if not isinstance(other, Vector3d): _NamedBase.others(self, other, name=name, up=up + 1) return other def parse(self, str3d, sep=_COMMA_, name=NN): '''Parse an C{"x, y, z"} string to a similar L{Vector3d} instance. @arg str3d: X, y and z string (C{str}), see function L{parse3d}. @kwarg sep: Optional separator (C{str}). @kwarg name: Optional instance name (C{str}), overriding this name. @return: The similar instance (L{Vector3d}). @raise VectorError: Invalid B{C{str3d}}. ''' return parse3d(str3d, sep=sep, Vector=self.classof, name=name or self.name) def plus(self, other): '''Add this vector and an other vector. @arg other: The other vector (L{Vector3d}). @return: Vectorial sum (L{Vector3d}). @raise TypeError: Incompatible B{C{other}} C{type}. ''' self.others(other) return self.classof(self.x + other.x, self.y + other.y, self.z + other.z) sum = plus # alternate name def rotate(self, axis, theta): '''Rotate this vector around an axis by a specified angle. See U{Rotation matrix from axis and angle <https://WikiPedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle>} and U{Quaternion-derived rotation matrix <https://WikiPedia.org/wiki/Quaternions_and_spatial_rotation#Quaternion-derived_rotation_matrix>}. @arg axis: The axis being rotated around (L{Vector3d}). @arg theta: The angle of rotation (C{radians}). @return: New, rotated vector (L{Vector3d}). @JSname: I{rotateAround}. ''' a = self.others(axis=axis).unit() # axis being rotated around c = cos(theta) b = a.times(1 - c) s = a.times(sin(theta)) p = self.unit().xyz # point being rotated # multiply p by a quaternion-derived rotation matrix return self.classof(fdot(p, a.x * b.x + c, a.x * b.y - s.z, a.x * b.z + s.y), fdot(p, a.y * b.x + s.z, a.y * b.y + c, a.y * b.z - s.x), fdot(p, a.z * b.x - s.y, a.z * b.y + s.x, a.z * b.z + c)) def rotateAround(self, axis, theta): # PYCHOK no cover '''DEPRECATED, use method C{rotate}. ''' return self.rotate(axis, theta) def times(self, factor): '''Multiply this vector by a scalar. @arg factor: Scale factor (C{scalar}). @return: New, scaled vector (L{Vector3d}). @raise TypeError: Non-scalar B{C{factor}}. ''' if not isscalar(factor): raise _IsnotError(_scalar_, factor=factor) return self.classof(self.x * factor, self.y * factor, self.z * factor) def to2ab(self): # PYCHOK no cover '''DEPRECATED, use property C{Nvector.philam}. @return: A L{PhiLam2Tuple}C{(phi, lam)}. ''' return n_xyz2philam(self.x, self.y, self.z) def to2ll(self): # PYCHOK no cover '''DEPRECATED, use property C{Nvector.latlon}. @return: A L{LatLon2Tuple}C{(lat, lon)}. ''' return n_xyz2latlon(self.x, self.y, self.z) def to3xyz(self): # PYCHOK no cover '''DEPRECATED, use property C{xyz}. @return: A L{Vector3Tuple}C{(x, y, z)}. ''' return self.xyz def toStr(self, prec=5, fmt=Fmt.PAREN, sep=_COMMASPACE_): # PYCHOK expected '''Return a string representation of this vector. @kwarg prec: Optional number of decimal places (C{int}). @kwarg fmt: Optional, enclosing format to use (C{str}). @kwarg sep: Optional separator between components (C{str}). @return: Vector as "(x, y, z)" (C{str}). ''' t = sep.join(strs(self.xyz, prec=prec)) return (fmt % (t,)) if fmt else t def trilaterate3d2(self, radius, center2, radius2, center3, radius3, eps=EPS): '''Trilaterate this and two other spheres, each given as a (3d) center and radius. @arg radius: Radius of this sphere (same C{units} as this C{x}, C{y} and C{z}). @arg center2: Center of the 2nd sphere (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}). @arg radius2: Radius of this sphere (same C{units} as this C{x}, C{y} and C{z}). @arg center3: Center of the 3rd sphere (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}). @arg radius3: Radius of the 3rd sphere (same C{units} as this C{x}, C{y} and C{z}). @kwarg eps: Tolerance (C{scalar}), same units as C{x}, C{y}, and C{z}. @return: 2-Tuple with two trilaterated points, each an instance of this L{Vector3d} (sub-)class. Both points are the same instance if all three spheres intersect or abut in a single point. @raise ImportError: Package C{numpy} not found, not installed or older than version 1.15. @raise IntersectionError: No intersection, colinear or near concentric centers or trilateration failed some other way. @raise TypeError: Invalid B{C{center2}} or B{C{center3}}. @raise UnitError: Invalid B{C{radius}}, B{C{radius2}} or B{C{radius3}}. @note: Package U{numpy<https://pypi.org/project/numpy>} is required, version 1.15 or later. @see: Norrdine, A. U{I{An Algebraic Solution to the Multilateration Problem}<https://www.ResearchGate.net/publication/ 275027725_An_Algebraic_Solution_to_the_Multilateration_Problem>} and U{I{implementation}<https://www.ResearchGate.net/publication/ 288825016_Trilateration_Matlab_Code>}. ''' try: return _trilaterate3d2(self if self.name else _otherV3d(center=self), Radius_(radius, low=eps), center2, radius2, center3, radius3, eps=eps, Vector=self.classof) except (AssertionError, FloatingPointError) as x: raise IntersectionError(center=self, radius=radius, center2=center2, radius2=radius2, center3=center3, radius3=radius3, txt=str(x)) def unit(self, ll=None): '''Normalize this vector to unit length. @kwarg ll: Optional, original location (C{LatLon}). @return: Normalized vector (L{Vector3d}). ''' if self._united is None: n = self.length if n > EPS and abs(n - 1) > EPS: u = self._xnamed(self.dividedBy(n)) u._length = 1 else: u = self.copy() u._fromll = ll or self._fromll self._united = u._united = u return self._united @property_RO def x(self): '''Get the X component (C{float}). ''' return self._x @property_RO def xyz(self): '''Get the X, Y and Z components (L{Vector3Tuple}C{(x, y, z)}). ''' if self._xyz is None: self._xyz = Vector3Tuple(self.x, self.y, self.z) return self._xnamed(self._xyz) @property_RO def y(self): '''Get the Y component (C{float}). ''' return self._y @property_RO def z(self): '''Get the Z component (C{float}). ''' return self._z def intersections2(center1, radius1, center2, radius2, sphere=True, Vector=None, **Vector_kwds): '''Compute the intersection of two spheres or circles, each defined by a center point and a radius. @arg center1: Center of the first sphere or circle (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}). @arg radius1: Radius of the first sphere or circle (same units as the B{C{center1}} coordinates). @arg center2: Center of the second sphere or circle (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}). @arg radius2: Radius of the second sphere or circle (same units as the B{C{center1}} and B{C{center2}} coordinates). @kwarg sphere: If C{True} compute the center and radius of the intersection of two spheres. If C{False}, ignore the C{z}-component and compute the intersection of two circles (C{bool}). @kwarg Vector: Class to return intersections (L{Vector3d} or C{Vector3Tuple}) or C{None} for L{Vector3d}. @kwarg Vector_kwds: Optional, additional B{C{Vector}} keyword arguments, ignored if C{B{Vector}=None}. @return: If B{C{sphere}} is C{True}, a 2-Tuple of the C{center} and C{radius} of the intersection of the spheres. The C{radius} is C{0.0} for abutting spheres. If B{C{sphere}} is C{False}, a 2-tuple of the intersection points of two circles. For abutting circles, both points are the same B{C{Vector}} instance. @raise IntersectionError: Concentric, invalid or non-intersecting spheres or circles. @raise UnitError: Invalid B{C{radius1}} or B{C{radius2}}. @see: U{Sphere-Sphere<https://MathWorld.Wolfram.com/Sphere- SphereIntersection.html>} and U{circle-circle <https://MathWorld.Wolfram.com/Circle-CircleIntersection.html>} intersections. ''' try: return _intersects2(center1, Radius_(radius1=radius1), center2, Radius_(radius2=radius2), sphere=sphere, Vector=Vector, **Vector_kwds) except (TypeError, ValueError) as x: raise IntersectionError(center1=center1, radius1=radius1, center2=center2, radius2=radius2, txt=str(x)) def _intersects2(center1, r1, center2, r2, sphere=True, too_d=None, # in .ellipsoidalBase._intersections2 Vector=None, **Vector_kwds): # (INTERNAL) Intersect two spheres or circles, see L{intersections2} # above, separated to allow callers to embellish any exceptions def _V3(x, y, z): v = Vector3d(x, y, z) n = intersections2.__name__ return _V_n(v, n, Vector, Vector_kwds) def _xV3(c1, u, x, y): xy1 = x, y, _1_0 # transform to original space return _V3(fdot(xy1, u.x, -u.y, c1.x), fdot(xy1, u.y, u.x, c1.y), _0_0) c1 = _otherV3d(sphere=sphere, center1=center1) c2 = _otherV3d(sphere=sphere, center2=center2) if r1 < r2: # r1, r2 == R, r c1, c2 = c2, c1 r1, r2 = r2, r1 m = c2.minus(c1) d = m.length if d < max(r2 - r1, EPS): raise ValueError(_near_concentric_) o = fsum_(-d, r1, r2) # overlap == -(d - (r1 + r2)) # compute intersections with c1 at (0, 0) and c2 at (d, 0), like # <https://MathWorld.Wolfram.com/Circle-CircleIntersection.html> if o > EPS: # overlapping, r1, r2 == R, r x = _radical2(d, r1, r2).xline y = _1_0 - (x / r1)**2 if y > EPS: y = r1 * sqrt(y) # y == a / 2 elif y < 0: raise ValueError(_invalid_) else: # abutting y = _0_0 elif o < 0: t = d if too_d is None else too_d raise ValueError(_too_(Fmt.distant(t))) else: # abutting x, y = r1, _0_0 u = m.unit() if sphere: # sphere center and radius c = c1 if x < EPS else ( c2 if x > EPS1 else c1.plus(u.times(x))) t = _V3(c.x, c.y, c.z), Radius(y) elif y > 0: # intersecting circles t = _xV3(c1, u, x, y), _xV3(c1, u, x, -y) else: # abutting circles t = _xV3(c1, u, x, 0) t = t, t return t def iscolinearWith(point, point1, point2, eps=EPS): '''Check whether a point is colinear with two other points. @arg point: The point (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}). @arg point1: Another point (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}). @arg point2: Another point (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}). @kwarg eps: Tolerance (C{scalar}), same units as C{x}, C{y} and C{z}. @return: C{True} if colinear, C{False} otherwise. @raise TypeError: Invalid B{C{point}}, B{C{point1}} or B{C{point2}}. @see: Function L{nearestOn}. ''' return _iscolinearWith(_V3d(point) or _otherV3d(point=point), point1, point2, eps=eps) def _iscolinearWith(v, p1, p2, eps=EPS): # (INTERNAL) Check colinear, see L{isColinear} above, # separated to allow callers to embellish any exceptions v1 = _V3d(p1) or _otherV3d(point1=p1) v2 = _V3d(p2) or _otherV3d(point2=p2) n = _nearestOn(v, v1, v2, within=False, eps=eps) return n is v1 or n.minus(v).length2 < eps def nearestOn(point, point1, point2, within=True, Vector=None, **Vector_kwds): '''Locate the point between two points closest to a reference. @arg point: Reference point (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}). @arg point1: Start point (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}). @arg point2: End point (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}). @kwarg within: If C{True} return the closest point between both given points, otherwise the closest point on the extended line through both points (C{bool}). @kwarg Vector: Class to return closest point (L{Vector3d} or C{Vector3Tuple}) or C{None} for L{Vector3d}. @kwarg Vector_kwds: Optional, additional B{C{Vector}} keyword arguments, ignored if C{B{Vector}=None}. @return: Closest point (L{Vector3d} or C{Vector}). @raise TypeError: Invalid B{C{point}}, B{C{point1}} or B{C{point2}}. @see: Methods L{sphericalTrigonometry.LatLon.nearestOn3} and L{sphericalTrigonometry.LatLon.nearestOn3} U{3-D Point-Line distance<https://MathWorld.Wolfram.com/ Point-LineDistance3-Dimensional.html>}. ''' v = _nearestOn(_V3d(point) or _otherV3d(point =point), _V3d(point1) or _otherV3d(point1=point1), _V3d(point2) or _otherV3d(point2=point2), within=within) return _V_n(v, nearestOn.__name__, Vector, Vector_kwds) def _nearestOn(p0, p1, p2, within=True, eps=EPS): # (INTERNAL) Get closest point, see L{nearestOn} above, # separated to allow callers to embellish any exceptions p21 = p2.minus(p1) d2 = p21.length2 if d2 < eps: # coincident p = p1 # ... or p2 else: t = p0.minus(p1).dot(p21) / d2 p = p1 if (within and t < eps) else ( p2 if (within and t > (_1_0 - eps)) else p1.plus(p21.times(t))) return p def _null_space2(numpy, A, eps): # (INTERNAL) Return the nullspace and rank of matrix A # @see: <https://SciPy-Cookbook.ReadTheDocs.io/items/RankNullspace.html>, # <https://NumPy.org/doc/stable/reference/generated/numpy.linalg.svd.html>, # <https://StackOverflow.com/questions/19820921>, # <https://StackOverflow.com/questions/2992947> and # <https://StackOverflow.com/questions/5889142> A = numpy.array(A) m = max(numpy.shape(A)) if m != 4: # for this usage raise _AssertionError(shape=m, txt=modulename(_null_space2, True)) # if needed, square A, pad with zeros A = numpy.resize(A, m * m).reshape(m, m) # try: # no numpy.linalg.null_space <https://docs.SciPy.org/doc/> # return scipy.linalg.null_space(A) # XXX no scipy.linalg? # except AttributeError: # pass _, s, v = numpy.linalg.svd(A) t = max(eps, eps * s[0]) # tol, s[0] is largest singular r = numpy.sum(s > t) # rank if r == 3: # get null_space n = numpy.transpose(v[r:]) s = numpy.shape(n) if s != (m, 1): # bad null_space shape raise _AssertionError(shape=s, txt=modulename(_null_space2, True)) e = float(numpy.max(numpy.abs(numpy.dot(A, n)))) if e > t: # residual not near-zero raise _AssertionError(eps=e, txt=modulename(_null_space2, True)) else: # coincident, colinear, concentric centers, ambiguous, etc. n = None # del A, s, vh # release numpy return n, r def _otherV3d(sphere=True, **name_v): # check B{C{name#}} vector instance, return Vector3d name, v = _xkwds_popitem(name_v) try: return Vector3d(v.x, v.y, v.z if sphere else _0_0, name=name) except AttributeError: # no _x_ or _y_ attr pass raise _xotherError(Vector3d(0, 0, 0), v, name=name, up=2) def parse3d(str3d, sep=_COMMA_, name=NN, Vector=Vector3d, **Vector_kwds): '''Parse an C{"x, y, z"} string. @arg str3d: X, y and z values (C{str}). @kwarg sep: Optional separator (C{str}). @kwarg name: Optional instance name (C{str}). @kwarg Vector: Optional class (L{Vector3d}). @kwarg Vector_kwds: Optional B{C{Vector}} keyword arguments, ignored if C{B{Vector}=None}. @return: New B{C{Vector}} or if B{C{Vector}} is C{None}, a L{Vector3Tuple}C{(x, y, z)}. @raise VectorError: Invalid B{C{str3d}}. ''' try: v = [float(v.strip()) for v in str3d.split(sep)] n = len(v) if n != 3: raise _ValueError(len=n) except (TypeError, ValueError) as x: raise VectorError(str3d=str3d, txt=str(x)) return _V_n(Vector3Tuple(*v), name, Vector, Vector_kwds) def sumOf(vectors, Vector=Vector3d, **Vector_kwds): '''Compute the vectorial sum of several vectors. @arg vectors: Vectors to be added (L{Vector3d}[]). @kwarg Vector: Optional class for the vectorial sum (L{Vector3d}). @kwarg Vector_kwds: Optional B{C{Vector}} keyword arguments, ignored if C{B{Vector}=None}. @return: Vectorial sum as B{C{Vector}} or if B{C{Vector}} is C{None}, a L{Vector3Tuple}C{(x, y, z)}. @raise VectorError: No B{C{vectors}}. ''' n, vectors = len2(vectors) if n < 1: raise VectorError(vectors=n, txt=MISSING) v = Vector3Tuple(fsum(v.x for v in vectors), fsum(v.y for v in vectors), fsum(v.z for v in vectors)) return _V_n(v, sumOf.__name__, Vector, Vector_kwds) def trilaterate3d2(center1, radius1, center2, radius2, center3, radius3, eps=EPS, Vector=None, **Vector_kwds): '''Trilaterate three spheres, each given as a (3d) center point and radius. @arg center1: Center of the 1st sphere (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}). @arg radius1: Radius of the 1st sphere (same C{units} as C{x}, C{y} and C{z}). @arg center2: Center of the 2nd sphere (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}). @arg radius2: Radius of this sphere (same C{units} as C{x}, C{y} and C{z}). @arg center3: Center of the 3rd sphere (L{Vector3d}, C{Vector3Tuple} or C{Vector4Tuple}). @arg radius3: Radius of the 3rd sphere (same C{units} as C{x}, C{y} and C{z}). @kwarg eps: Tolerance (C{scalar}), same units as C{x}, C{y}, and C{z}. @kwarg Vector: Class to return intersections (L{Vector3d} or C{Vector3Tuple}) or C{None} for L{Vector3d}. @kwarg Vector_kwds: Optional, additional B{C{Vector}} keyword arguments, ignored if C{B{Vector}=None}. @return: 2-Tuple with two trilaterated points, each a B{C{Vector}} instance. Both points are the same instance if all three spheres abut/intersect in a single point. @raise ImportError: Package C{numpy} not found, not installed or older than version 1.15. @raise IntersectionError: No intersection, colinear or concentric centers or trilateration failed some other way. @raise TypeError: Invalid B{C{center1}}, B{C{center2}} or B{C{center3}}. @raise UnitError: Invalid B{C{radius1}}, B{C{radius2}} or B{C{radius3}}. @note: Package U{numpy<https://pypi.org/project/numpy>} is required, version 1.15 or later. @see: Norrdine, A. U{I{An Algebraic Solution to the Multilateration Problem}<https://www.ResearchGate.net/publication/ 275027725_An_Algebraic_Solution_to_the_Multilateration_Problem>} and U{I{implementation}<https://www.ResearchGate.net/publication/ 288825016_Trilateration_Matlab_Code>}. ''' try: return _trilaterate3d2(_otherV3d(center1=center1), Radius_(radius1=radius1, low=eps), center2, radius2, center3, radius3, eps=eps, Vector=Vector, **Vector_kwds) except (AssertionError, FloatingPointError) as x: raise IntersectionError(center1=center1, radius1=radius1, center2=center2, radius2=radius2, center3=center3, radius3=radius3, txt=str(x)) def _trilaterate3d2(c1, r1, c2, r2, c3, r3, eps=EPS, Vector=None, **Vector_kwds): # MCCABE 13 # (INTERNAL) Intersect three spheres or circles, see L{trilaterate3d2} # above, separated to allow callers to embellish any exceptions def _0f3d(F): # map numpy 4-vector to floats and split F0, x, y, z = map(float, F) return F0, Vector3d(x, y, z) def _N3(t01, x, z): # compute x, y and z and return as Vector v = x.plus(z.times(t01)) n = trilaterate3d2.__name__ return _V_n(v, n, Vector, Vector_kwds) def _real_roots(numpy, *coeffs): # non-complex roots of a polynomial rs = numpy.polynomial.polynomial.polyroots(coeffs) return tuple(float(r) for r in rs if not numpy.iscomplex(r)) def _txt(c1, r1, c2, r2): # check for concentric or too distant spheres d = c1.minus(c2).length if d < abs(r1 - r2): t = _near_concentric_ elif d > (r1 + r2): t = _too_(Fmt.distant(d)) else: return NN return _SPACE_(c1.name, 'and', c2.name, t) np = Vector3d._numpy if np is None: # get numpy, once or ImportError Vector3d._numpy = np = _xnumpy(trilaterate3d2, 1, 10) # macOS' Python 2.7 numpy 1.8 OK c2 = _otherV3d(center2=c2) c3 = _otherV3d(center3=c3) A = [] # 3 x 4 b = [] # 1 x 3 or 3 x 1 for c, d in ((c1, r1), (c2, Radius_(radius2=r2, low=eps)), (c3, Radius_(radius3=r3, low=eps))): A.append((_1_0, -2 * c.x, -2 * c.y, -2 * c.z)) b.append(d**2 - c.length2) try: # <https://NumPy.org/doc/stable/reference/generated/numpy.seterr.html> e = np.seterr(all='raise') # throw FloatingPointError for numpy errors X = np.dot(np.linalg.pinv(A), b) # Moore-Penrose pseudo-inverse Z, _ = _null_space2(np, A, eps) if Z is None: t = () # coincident, colinear, concentric, etc. else: X0, x = _0f3d(X) Z0, z = _0f3d(Z) # quadratic polynomial coefficients, ordered (^0, ^1, ^2) t = _real_roots(np, x.length2 - X0, # fdot(X, -_1_0, *x.xyz) z.dot(x) * 2 - Z0, # fdot(Z, -_0_5, *x.xyz) * 2 z.length2) # fdot(Z, _0_0, *z.xyz) finally: # restore numpy error handling np.seterr(**e) if not t: # coincident, colinear, too distant, no intersection, etc. raise FloatingPointError(_txt(c1, r1, c2, r2) or _txt(c1, r1, c3, r3) or _txt(c2, r2, c3, r3) or (_colinear_ if _iscolinearWith(c1, c2, c3, eps=eps) else _no_(_intersection_))) elif len(t) < 2: # one intersection t *= 2 v = _N3(t[0], x, z) if abs(t[0] - t[1]) < eps: # abutting t = v, v else: # "lowest" intersection first (to avoid test failures) u = _N3(t[1], x, z) t = (u, v) if u < v else (v, u) return t def _V3d(v3d): # return v3d if it's a L{Vector3d} instance return v3d if isinstance(v3d, Vector3d) else None def _V_n(v, name, Vector, Vector_kwds): # return a named Vector instance if Vector is None: v = _xnamed(v, name) else: kwds = _xkwds(Vector_kwds, name=name) v = Vector(v.x, v.y, v.z, **kwds) return v __all__ += _ALL_DOCS(intersections2, sumOf) # **) MIT License # # Copyright (C) 2016-2021 -- mrJean1 at Gmail -- All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE.