forked from rai-opensource/spatialmath-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvectors.py
More file actions
868 lines (635 loc) · 21.6 KB
/
vectors.py
File metadata and controls
868 lines (635 loc) · 21.6 KB
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
# Part of Spatial Math Toolbox for Python
# Copyright (c) 2000 Peter Corke
# MIT Licence, see details in top-level file: LICENCE
"""
Functions to manipulate vectors
Vector arguments are what numpy refers to as ``array_like`` and can be a list,
tuple, numpy array, numpy row vector or numpy column vector.
"""
# pylint: disable=invalid-name
import math
import numpy as np
from spatialmath.base.argcheck import getvector
from spatialmath.base.types import *
try: # pragma: no cover
# print('Using SymPy')
import sympy
_symbolics = True
except ImportError: # pragma: no cover
_symbolics = False
_eps = np.finfo(np.float64).eps
def norm(v: ArrayLikePure) -> float:
"""
Norm of vector
:param v: any vector
:type v: array_like(n)
:return: norm of vector
:rtype: float
``norm(v)`` is the 2-norm (length or magnitude) of the vector ``v``.
.. runblock:: pycon
>>> from spatialmath.base import *
>>> norm([3, 4])
.. note:: This function does not use NumPy, it is ~2x faster than
`numpy.linalg.norm()` for a 3-vector
:seealso: :func:`~spatialmath.base.unit`
:SymPy: supported
"""
sum = 0
for x in v:
sum += x * x
if _symbolics and isinstance(sum, sympy.Expr):
return sympy.sqrt(sum)
else:
return math.sqrt(sum)
def normsq(v: ArrayLikePure) -> float:
"""
Squared norm of vector
:param v: any vector
:type v: array_like(n)
:return: norm of vector
:rtype: float
``norm(sq)`` is the sum of squared elements of the vector ``v``
or :math:`|v|^2`.
.. runblock:: pycon
>>> from spatialmath.base import *
>>> normsq([2, 3])
.. note:: This function does not use NumPy, it is ~2x faster than
`numpy.linalg.norm() ** 2` for a 3-vector
:seealso: :func:`~spatialmath.base.unit`
:SymPy: supported
"""
sum = 0
for x in v:
sum += x * x
return sum
def cross(u: ArrayLike3, v: ArrayLike3) -> R3:
"""
Cross product of vectors
:param u: any vector
:type u: array_like(3)
:param v: any vector
:type v: array_like(3)
:return: cross product
:rtype: nd.array(3)
``cross(u, v)`` is the cross product of the vectors ``u`` and ``v``.
.. runblock:: pycon
>>> from spatialmath.base import *
>>> cross([1, 0, 0], [0, 1, 0])
.. note:: This function does not use NumPy, it is ~1.5x faster than
`numpy.cross()`
:seealso: :func:`~spatialmath.base.unit`
:SymPy: supported
"""
return np.r_[
u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]
]
def colvec(v: ArrayLike) -> NDArray:
"""
Create a column vector
:param v: any vector
:type v: array_like(n)
:return: a column vector
:rtype: ndarray(n,1)
Convert input to a column vector.
.. runblock:: pycon
>>> from spatialmath.base import *
>>> colvec([1, 2, 3])
"""
v = getvector(v)
return np.array(v).reshape((len(v), 1))
def unitvec(v: ArrayLike, tol: float = 20) -> NDArray:
"""
Create a unit vector
:param v: any vector
:type v: array_like(n)
:param tol: Tolerance in units of eps for zero-norm case, defaults to 20
:type: float
:return: a unit-vector parallel to ``v``.
:rtype: ndarray(n)
:raises ValueError: for zero length vector
``unitvec(v)`` is a vector parallel to `v` of unit length.
.. runblock:: pycon
>>> from spatialmath.base import *
>>> unitvec([3, 4])
:seealso: :func:`~numpy.linalg.norm`
"""
v = getvector(v)
n = norm(v)
if n > tol * _eps: # if greater than eps
return v / n
else:
raise ValueError("zero norm vector")
def unitvec_norm(v: ArrayLike, tol: float = 20) -> Tuple[NDArray, float]:
"""
Create a unit vector
:param v: any vector
:type v: array_like(n)
:param tol: Tolerance in units of eps for zero-norm case, defaults to 20
:type: float
:return: a unit-vector parallel to ``v`` and the norm
:rtype: (ndarray(n), float)
:raises ValueError: for zero length vector
``unitvec(v)`` is a vector parallel to `v` of unit length.
.. runblock:: pycon
>>> from spatialmath.base import *
>>> unitvec([3, 4])
:seealso: :func:`~numpy.linalg.norm`
"""
v = getvector(v)
nm = norm(v)
if nm > tol * _eps: # if greater than eps
return (v / nm, nm)
else:
raise ValueError("zero norm vector")
def isunitvec(v: ArrayLike, tol: float = 20) -> bool:
"""
Test if vector has unit length
:param v: vector to test
:type v: ndarray(n)
:param tol: tolerance in units of eps, defaults to 20
:type tol: float
:return: whether vector has unit length
:rtype: bool
.. runblock:: pycon
>>> from spatialmath.base import *
>>> isunitvec([1, 0])
>>> isunitvec([1, 2])
:seealso: unit, iszerovec, isunittwist
"""
return bool(abs(np.linalg.norm(v) - 1) < tol * _eps)
def iszerovec(v: ArrayLike, tol: float = 20) -> bool:
"""
Test if vector has zero length
:param v: vector to test
:type v: ndarray(n)
:param tol: tolerance in units of eps, defaults to 20
:type tol: float
:return: whether vector has zero length
:rtype: bool
.. runblock:: pycon
>>> from spatialmath.base import *
>>> iszerovec([0, 0])
>>> iszerovec([1, 2])
:seealso: unit, isunitvec, isunittwist
"""
return bool(np.linalg.norm(v) < tol * _eps)
def iszero(v: float, tol: float = 20) -> bool:
"""
Test if scalar is zero
:param v: value to test
:type v: float
:param tol: tolerance in units of eps, defaults to 20
:type tol: float
:return: whether value is zero
:rtype: bool
.. runblock:: pycon
>>> from spatialmath.base import *
>>> iszero(0)
>>> iszero(1)
:seealso: unit, iszerovec, isunittwist
"""
return bool(abs(v) < tol * _eps)
def isunittwist(v: ArrayLike6, tol: float = 20) -> bool:
r"""
Test if vector represents a unit twist in SE(2) or SE(3)
:param v: twist vector to test
:type v: array_like(6)
:param tol: tolerance in units of eps, defaults to 20
:type tol: float
:return: whether twist has unit length
:rtype: bool
:raises ValueError: for incorrect vector length
Vector is is intepretted as :math:`[v, \omega]` where :math:`v \in \mathbb{R}^n` and
:math:`\omega \in \mathbb{R}^1` for SE(2) and :math:`\omega \in \mathbb{R}^3` for SE(3).
A unit twist can be a:
- unit rotational twist where :math:`|| \omega || = 1`, or
- unit translational twist where :math:`|| \omega || = 0` and :math:`|| v || = 1`.
.. runblock:: pycon
>>> from spatialmath.base import *
>>> isunittwist([1, 2, 3, 1, 0, 0])
>>> isunittwist([0, 0, 0, 2, 0, 0])
:seealso: unit, isunitvec
"""
v = getvector(v)
if len(v) == 6:
# test for SE(3) twist
return isunitvec(v[3:6], tol=tol) or (
iszerovec(v[3:6], tol=tol) and isunitvec(v[0:3], tol=tol)
)
else:
raise ValueError
def isunittwist2(v: ArrayLike3, tol: float = 20) -> bool:
r"""
Test if vector represents a unit twist in SE(2) or SE(3)
:param v: twist vector to test
:type v: array_like(3)
:param tol: tolerance in units of eps, defaults to 20
:type tol: float
:return: whether vector has unit length
:rtype: bool
:raises ValueError: for incorrect vector length
Vector is is intepretted as :math:`[v, \omega]` where :math:`v \in \mathbb{R}^n` and
:math:`\omega \in \mathbb{R}^1` for SE(2) and :math:`\omega \in \mathbb{R}^3` for SE(3).
A unit twist can be a:
- unit rotational twist where :math:`|| \omega || = 1`, or
- unit translational twist where :math:`|| \omega || = 0` and :math:`|| v || = 1`.
.. runblock:: pycon
>>> from spatialmath.base import *
>>> isunittwist2([1, 2, 1])
>>> isunittwist2([0, 0, 2])
:seealso: unit, isunitvec
"""
v = getvector(v)
if len(v) == 3:
# test for SE(2) twist
return isunitvec(v[2], tol=tol) or (
iszero(v[2], tol=tol) and isunitvec(v[0:2], tol=tol)
)
else:
raise ValueError
def unittwist(S: ArrayLike6, tol: float = 20) -> Union[R6, None]:
"""
Convert twist to unit twist
:param S: twist vector
:type S: array_like(6)
:param tol: tolerance in units of eps, defaults to 20
:type tol: float
:return: unit twist
:rtype: ndarray(6)
A unit twist is a twist where:
- the rotation part has unit magnitude
- if the rotational part is zero, then the translational part has unit magnitude
.. runblock:: pycon
>>> from spatialmath.base import *
>>> unittwist([2, 4, 6, 2, 0, 0])
>>> unittwist([2, 0, 0, 0, 0, 0])
Returns None if the twist has zero magnitude
"""
S = getvector(S, 6)
if iszerovec(S, tol=tol):
return None
v = S[0:3]
w = S[3:6]
if iszerovec(w, tol=tol):
th = norm(v)
else:
th = norm(w)
return S / th
def unittwist_norm(
S: Union[R6, ArrayLike6], tol: float = 20
) -> Tuple[Union[R6, None], Union[float, None]]:
"""
Convert twist to unit twist and norm
:param S: twist vector
:type S: array_like(6)
:param tol: tolerance in units of eps, defaults to 20
:type tol: float
:return: unit twist and scalar motion
:rtype: tuple (ndarray(6), float)
A unit twist is a twist where:
- the rotation part has unit magnitude
- if the rotational part is zero, then the translational part has unit magnitude
.. runblock:: pycon
>>> from spatialmath.base import *
>>> S, n = unittwist_norm([1, 2, 3, 1, 0, 0])
>>> print(S, n)
>>> S, n = unittwist_norm([0, 0, 0, 2, 0, 0])
>>> print(S, n)
>>> S, n = unittwist_norm([0, 0, 0, 0, 0, 0])
>>> print(S, n)
.. note:: Returns (None,None) if the twist has zero magnitude
"""
S = getvector(S, 6)
if iszerovec(S, tol=tol):
return (None, None) # according to "note" in docstring.
v = S[0:3]
w = S[3:6]
if iszerovec(w, tol=tol):
th = norm(v)
else:
th = norm(w)
return (S / th, th)
def unittwist2(S: ArrayLike3, tol: float = 20) -> Union[R3, None]:
"""
Convert twist to unit twist
:param S: twist vector
:type S: array_like(3)
:param tol: tolerance in units of eps, defaults to 20
:type tol: float
:return: unit twist
:rtype: ndarray(3)
A unit twist is a twist where:
- the rotation part has unit magnitude
- if the rotational part is zero, then the translational part has unit magnitude
.. runblock:: pycon
>>> from spatialmath.base import *
>>> unittwist2([2, 4, 2)
>>> unittwist2([2, 0, 0])
.. note:: Returns None if the twist has zero magnitude
"""
S = getvector(S, 3)
if iszerovec(S, tol=tol):
return None
v = S[0:2]
w = S[2]
if iszero(w, tol=tol):
th = norm(v)
else:
th = abs(w)
return S / th
def unittwist2_norm(
S: ArrayLike3, tol: float = 20
) -> Tuple[Union[R3, None], Union[float, None]]:
"""
Convert twist to unit twist
:param S: twist vector
:type S: array_like(3)
:param tol: tolerance in units of eps, defaults to 20
:type tol: float
:return: unit twist and scalar motion
:rtype: tuple (ndarray(3), float)
A unit twist is a twist where:
- the rotation part has unit magnitude
- if the rotational part is zero, then the translational part has unit magnitude
.. runblock:: pycon
>>> from spatialmath.base import *
>>> unittwist2([2, 4, 2)
>>> unittwist2([2, 0, 0])
.. note:: Returns (None, None) if the twist has zero magnitude
"""
S = getvector(S, 3)
if iszerovec(S, tol=tol):
return (None, None)
v = S[0:2]
w = S[2]
if iszero(w, tol=tol):
th = norm(v)
else:
th = abs(w)
return (S / th, th)
def wrap_0_pi(theta: ArrayLike) -> Union[float, NDArray]:
r"""
Wrap angle to range :math:`[0, \pi]`
:param theta: input angle
:type theta: scalar or ndarray
:return: angle wrapped into range :math:`[0, \pi)`
:rtype: scalar or ndarray
This is used to fold angles of colatitude. If zero is the angle of the
north pole, colatitude increases to :math:`\pi` at the south pole then
decreases to :math:`0` as we head back to the north pole.
:seealso: :func:`wrap_mpi2_pi2` :func:`wrap_0_2pi` :func:`wrap_mpi_pi` :func:`angle_wrap`
"""
theta = np.abs(getvector(theta))
n = theta / np.pi
if isinstance(n, np.ndarray):
n = n.astype(int)
else:
n = np.fix(n).astype(int)
y = np.where(np.bitwise_and(n, 1) == 0, theta - n * np.pi, (n + 1) * np.pi - theta)
if isinstance(y, np.ndarray) and y.size == 1:
return float(y[0])
else:
return y
def wrap_mpi2_pi2(theta: ArrayLike) -> Union[float, NDArray]:
r"""
Wrap angle to range :math:`[-\pi/2, \pi/2]`
:param theta: input angle
:type theta: scalar or ndarray
:return: angle wrapped into range :math:`[-\pi/2, \pi/2]`
:rtype: scalar or ndarray
This is used to fold angles of latitude.
:seealso: :func:`wrap_0_pi` :func:`wrap_0_2pi` :func:`wrap_mpi_pi` :func:`angle_wrap`
"""
theta = getvector(theta)
n = theta / np.pi * 2
if isinstance(n, np.ndarray):
n = n.astype(int)
else:
n = np.fix(n).astype(int)
y = np.where(np.bitwise_and(n, 1) == 0, theta - n * np.pi, n * np.pi - theta)
if isinstance(y, np.ndarray) and len(y) == 1:
return float(y[0])
else:
return y
def wrap_0_2pi(theta: ArrayLike) -> Union[float, NDArray]:
r"""
Wrap angle to range :math:`[0, 2\pi)`
:param theta: input angle
:type theta: scalar or ndarray
:return: angle wrapped into range :math:`[0, 2\pi)`
:rtype: scalar or ndarray
:seealso: :func:`wrap_mpi_pi` :func:`wrap_0_pi` :func:`wrap_mpi2_pi2` :func:`angle_wrap`
"""
theta = getvector(theta)
y = theta - 2.0 * math.pi * np.floor(theta / 2.0 / np.pi)
if isinstance(y, np.ndarray) and len(y) == 1:
return float(y[0])
else:
return y
def wrap_mpi_pi(theta: ArrayLike) -> Union[float, NDArray]:
r"""
Wrap angle to range :math:`[-\pi, \pi)`
:param theta: input angle
:type theta: scalar or ndarray
:return: angle wrapped into range :math:`[-\pi, \pi)`
:rtype: scalar or ndarray
:seealso: :func:`wrap_0_2pi` :func:`wrap_0_pi` :func:`wrap_mpi2_pi2` :func:`angle_wrap`
"""
theta = getvector(theta)
y = np.mod(theta + math.pi, 2 * math.pi) - np.pi
if isinstance(y, np.ndarray) and len(y) == 1:
return float(y[0])
else:
return y
# @overload
# def angdiff(a:ArrayLike):
# ...
@overload
def angdiff(a: ArrayLike, b: ArrayLike) -> NDArray:
...
@overload
def angdiff(a: ArrayLike) -> NDArray:
...
def angdiff(a, b=None):
r"""
Angular difference
:param a: angle in radians
:type a: scalar or array_like
:param b: angle in radians
:type b: scalar or array_like
:return: angular difference a-b
:rtype: scalar or array_like
- ``angdiff(a, b)`` is the difference ``a - b`` wrapped to the range
:math:`[-\pi, \pi)`. This is the operator :math:`a \circleddash b` used
in the RVC book
- If ``a`` and ``b`` are both scalars, the result is scalar
- If ``a`` is array_like, the result is a NumPy array ``a[i]-b``
- If ``a`` is array_like, the result is a NumPy array ``a-b[i]``
- If ``a`` and ``b`` are both vectors of the same length, the result is
a NumPy array ``a[i]-b[i]``
- ``angdiff(a)`` is the angle or vector of angles ``a`` wrapped to the range
:math:`[-\pi, \pi)`.
- If ``a`` is a scalar, the result is scalar
- If ``a`` is array_like, the result is a NumPy array
.. runblock:: pycon
>>> from spatialmath.base import *
>>> from math import pi
>>> angdiff(0, 2 * pi)
>>> angdiff(0.9 * pi, -0.9 * pi) / pi
>>> angdiff(3 * pi)
:seealso: :func:`vector_diff` :func:`wrap_mpi_pi`
"""
a = getvector(a)
if b is not None:
b = getvector(b)
a = a - b # cannot use -= here, numpy wont broadcast
y = np.mod(a + math.pi, 2 * math.pi) - math.pi
if isinstance(y, np.ndarray) and len(y) == 1:
return float(y[0])
else:
return y
def angle_std(theta: ArrayLike) -> float:
r"""
Standard deviation of angular values
:param theta: angular values
:type theta: array_like
:return: circular standard deviation
:rtype: float
.. math::
\sigma_{\theta} = \sqrt{-2 \log \| \left[ \frac{\sum \sin \theta_i}{N}, \frac{\sum \sin \theta_i}{N} \right] \|} \in [0, \infty)
:seealso: :func:`angle_mean`
"""
X = np.cos(theta).mean()
Y = np.sin(theta).mean()
R = np.sqrt(X**2 + Y**2)
return np.sqrt(-2 * np.log(R))
def angle_mean(theta: ArrayLike) -> float:
r"""
Mean of angular values
:param theta: angular values
:type v: array_like
:return: circular mean
:rtype: float
The circular mean is given by
.. math::
\bar{\theta} = \tan^{-1} \frac{\sum \sin \theta_i}{\sum \cos \theta_i} \in [-\pi, \pi)]
:seealso: :func:`angle_std`
"""
X = np.cos(theta).sum()
Y = np.sin(theta).sum()
return np.arctan2(Y, X)
def angle_wrap(theta: ArrayLike, mode: str = "-pi:pi") -> Union[float, NDArray]:
"""
Generalized angle-wrapping
:param v: angles to wrap
:type v: array_like
:param mode: wrapping mode, one of: ``"0:2pi"``, ``"0:pi"``, ``"-pi/2:pi/2"`` or ``"-pi:pi"`` [default]
:type mode: str, optional
:return: wrapped angles
:rtype: ndarray
.. note:: The modes ``"0:pi"`` and ``"-pi/2:pi/2"`` are used to wrap angles of
colatitude and latitude respectively.
:seealso: :func:`wrap_0_2pi` :func:`wrap_mpi_pi` :func:`wrap_0_pi` :func:`wrap_mpi2_pi2`
"""
if mode == "0:2pi":
return wrap_0_2pi(theta)
elif mode == "-pi:pi":
return wrap_mpi_pi(theta)
elif mode == "0:pi":
return wrap_0_pi(theta)
elif mode == "-pi/2:pi/2":
return wrap_mpi2_pi2(theta)
else:
raise ValueError("bad method specified")
def vector_diff(v1: ArrayLike, v2: ArrayLike, mode: str) -> NDArray:
"""
Generalized vector differnce
:param v1: first vector
:type v1: array_like(n)
:param v2: second vector
:type v2: array_like(n)
:param mode: subtraction mode
:type mode: str of length n
============== ====================================
mode character purpose
============== ====================================
r real number, don't wrap
c angle on circle, wrap to [-π, π)
C angle on circle, wrap to [0, 2π)
l latitude angle, wrap to [-π/2, π/2]
L colatitude angle, wrap to [0, π]
============== ====================================
:seealso: :func:`angdiff` :func:`wrap_0_2pi` :func:`wrap_mpi_pi` :func:`wrap_0_pi` :func:`wrap_mpi2_pi2`
"""
v = getvector(v1) - getvector(v2)
for i, m in enumerate(mode):
if m == "r":
pass
elif m == "c":
v[i] = wrap_mpi_pi(v[i])
elif m == "C":
v[i] = wrap_0_2pi(v[i])
elif m == "l":
v[i] = wrap_mpi2_pi2(v[i])
elif m == "L":
v[i] = wrap_0_pi(v[i])
else:
raise ValueError("bad mode character")
return v
def removesmall(v: ArrayLike, tol: float = 20) -> NDArray:
"""
Set small values to zero
:param v: any vector
:type v: array_like(n) or ndarray(n,m)
:param tol: Tolerance in units of eps, defaults to 20
:type tol: int, optional
:return: vector with small values set to zero
:rtype: ndarray(n) or ndarray(n,m)
Values with absolute value less than ``tol`` will be set to zero.
.. runblock:: pycon
>>> from spatialmath.base import *
>>> a = np.r_[1, 2, 3, 1e-16]
>>> print(a)
>>> a = removesmall(a)
>>> print(a)
>>> print(a[3])
"""
return np.where(np.abs(v) < tol * _eps, 0, v)
def project(v1: ArrayLike3, v2: ArrayLike3) -> ArrayLike3:
"""
Projects vector v1 onto v2. Returns a vector parallel to v2.
:param v1: vector to be projected
:type v1: array_like(n)
:param v2: vector to be projected onto
:type v2: array_like(n)
:return: vector projection of v1 onto v2 (parrallel to v2)
:rtype: ndarray(n)
"""
return np.dot(v1, v2) * v2
def orthogonalize(v1: ArrayLike3, v2: ArrayLike3, normalize: bool = True) -> ArrayLike3:
"""
Orthoginalizes vector v1 with respect to v2 with minimum rotation.
Returns a the nearest vector to v1 that is orthoginal to v2.
:param v1: vector to be orthoginalized
:type v1: array_like(n)
:param v2: vector that returned vector will be orthoginal to
:type v2: array_like(n)
:param normalize: whether to normalize the output vector
:type normalize: bool
:return: nearest vector to v1 that is orthoginal to v2
:rtype: ndarray(n)
"""
v_orth = v1 - project(v1, v2)
if normalize:
v_orth = v_orth / np.linalg.norm(v_orth)
return v_orth
if __name__ == "__main__": # pragma: no cover
import pathlib
exec(
open(
pathlib.Path(__file__).parent.parent.parent.absolute()
/ "tests"
/ "base"
/ "test_vectors.py"
).read()
) # pylint: disable=exec-used