forked from bdaiinstitute/spatialmath-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpose3d.py
2213 lines (1720 loc) · 72 KB
/
pose3d.py
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
# Part of Spatial Math Toolbox for Python
# Copyright (c) 2000 Peter Corke
# MIT Licence, see details in top-level file: LICENCE
"""
Classes to abstract 3D pose and orientation using matrices in SE(3) and SO(3)
To use::
from spatialmath.pose3d import *
T = SE3.Rx(0.3)
import spatialmath as sm
T = sm.SE3.Rx(0.3)
.. inheritance-diagram:: spatialmath.pose3d
:top-classes: collections.UserList
:parts: 1
.. image:: ../figs/pose-values.png
"""
from __future__ import annotations
# pylint: disable=invalid-name
import numpy as np
import spatialmath.base as smb
from spatialmath.base.types import *
from spatialmath.base.vectors import orthogonalize
from spatialmath.baseposematrix import BasePoseMatrix
from spatialmath.pose2d import SE2
from spatialmath.twist import Twist3
from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING:
from spatialmath.quaternion import UnitQuaternion
# ============================== SO3 =====================================#
class SO3(BasePoseMatrix):
"""
SO(3) matrix class
This subclass represents rotations in 3D space. Internally it is a 3x3
orthogonal matrix belonging to the group SO(3).
.. inheritance-diagram:: spatialmath.pose3d.SO3
:top-classes: collections.UserList
:parts: 1
"""
@overload
def __init__(self):
...
@overload
def __init__(self, arg: SO3, *, check=True):
...
@overload
def __init__(self, arg: SE3, *, check=True):
...
@overload
def __init__(self, arg: SO3Array, *, check=True):
...
@overload
def __init__(self, arg: List[SO3Array], *, check=True):
...
@overload
def __init__(self, arg: List[Union[SO3, SO3Array]], *, check=True):
...
def __init__(self, arg=None, *, check=True):
"""
Construct new SO(3) object
:rtype: SO3 instance
There are multiple call signatures:
- ``SO3()`` is an ``SO3`` instance with one value -- a 3x3 identity
matrix which corresponds to a null rotation
- ``SO3(R)`` is an ``SO3`` instance with with the value ``R`` which is a
3x3 numpy array representing an SO(3) rotation matrix. If ``check``
is ``True`` check the matrix belongs to SO(3).
- ``SO3([R1, R2, ... RN])`` is an ``SO3`` instance wwith ``N`` values
given by the elements ``Ri`` each of which is a 3x3 NumPy array
representing an SO(3) matrix. If ``check`` is ``True`` check the
matrix belongs to SO(3).
- ``SO3([X1, X2, ... XN])`` is an ``SO3`` instance with ``N`` values
given by the elements ``Xi`` each of which is an SO3 or SE3 instance.
:SymPy: supported
"""
super().__init__()
if isinstance(arg, SE3):
self.data = [smb.t2r(x) for x in arg.data]
elif not super().arghandler(arg, check=check):
raise ValueError("bad argument to constructor")
@staticmethod
def _identity() -> R3x3:
return np.eye(3)
# ------------------------------------------------------------------------ #
@property
def shape(self) -> Tuple[int, int]:
"""
Shape of the object's interal matrix representation
:return: (3,3)
:rtype: tuple
Each value within the ``SO3`` instance is a NumPy array of this shape.
"""
return (3, 3)
@property
def R(self) -> SO3Array:
"""
SO(3) or SE(3) as rotation matrix
:return: rotational component
:rtype: ndarray(3,3)
``x.R`` is the rotation matrix component of ``x`` as an array with
shape (3,3). If ``len(x) > 1``, return an array with shape=(N,3,3).
.. warning:: The i'th rotation matrix is ``x[i,:,:]`` or simply
``x[i]``. This is different to the MATLAB version where the i'th
rotation matrix is ``x(:,:,i)``.
Example:
.. runblock:: pycon
>>> from spatialmath import SO3
>>> x = SO3.Rx(0.3)
>>> x.R
:SymPy: supported
"""
if len(self) == 1:
return self.A[:3, :3] # type: ignore
else:
return np.array([x[:3, :3] for x in self.A]) # type: ignore
@property
def n(self) -> R3:
"""
Normal vector of SO(3) or SE(3)
:return: normal vector
:rtype: ndarray(3)
This is the first column of the rotation submatrix, sometimes called the
*normal vector*. It is parallel to the x-axis of the frame defined by
this pose.
"""
if len(self) != 1:
raise ValueError("can only determine n-vector for singleton pose")
return self.A[:3, 0] # type: ignore
@property
def o(self) -> R3:
"""
Orientation vector of SO(3) or SE(3)
:return: orientation vector
:rtype: ndarray(3)
This is the second column of the rotation submatrix, sometimes called
the *orientation vector*. It is parallel to the y-axis of the frame
defined by this pose.
"""
if len(self) != 1:
raise ValueError("can only determine o-vector for singleton pose")
return self.A[:3, 1] # type: ignore
@property
def a(self) -> R3:
"""
Approach vector of SO(3) or SE(3)
:return: approach vector
:rtype: ndarray(3)
This is the third column of the rotation submatrix, sometimes called the
*approach vector*. It is parallel to the z-axis of the frame defined by
this pose.
"""
if len(self) != 1:
raise ValueError("can only determine a-vector for singleton pose")
return self.A[:3, 2] # type: ignore
# ------------------------------------------------------------------------ #
def inv(self) -> Self:
"""
Inverse of SO(3)
:return: inverse
:rtype: SO2 instance
Efficiently compute the inverse of each of the SO(3) values taking into
account the matrix structure. For an SO(3) matrix the inverse is the
transpose.
"""
if len(self) == 1:
return SO3(self.A.T, check=False) # type: ignore
else:
return SO3([x.T for x in self.A], check=False)
def eul(self, unit: str = "rad", flip: bool = False) -> Union[R3, RNx3]:
r"""
SO(3) or SE(3) as Euler angles
:param unit: angular units: 'rad' [default], or 'deg'
:type unit: str
:return: 3-vector of Euler angles
:rtype: ndarray(3,), ndarray(n,3)
``x.eul`` is the Euler angle representation of the rotation. Euler angles are
a 3-vector :math:`(\phi, \theta, \psi)` which correspond to consecutive
rotations about the Z, Y, Z axes respectively.
If ``len(x)`` is:
- 1, return an ndarray with shape=(3,)
- N>1, return ndarray with shape=(3,N)
:seealso: :func:`~spatialmath.pose3d.SE3.Eul`, :func:`~spatialmath.base.transforms3d.tr2eul`
:SymPy: not supported
"""
if len(self) == 1:
return smb.tr2eul(self.A, unit=unit, flip=flip) # type: ignore
else:
return np.array([base.tr2eul(x, unit=unit, flip=flip) for x in self.A])
def rpy(self, unit: str = "rad", order: str = "zyx") -> Union[R3, RNx3]:
"""
SO(3) or SE(3) as roll-pitch-yaw angles
:param order: angle sequence order, default to 'zyx'
:type order: str
:param unit: angular units: 'rad' [default], or 'deg'
:type unit: str
:return: 3-vector of roll-pitch-yaw angles
:rtype: ndarray(3,), ndarray(n,3)
``x.rpy`` is the roll-pitch-yaw angle representation of the rotation. The angles are
a 3-vector :math:`(r, p, y)` which correspond to successive rotations about the axes
specified by ``order``:
- ``'zyx'`` [default], rotate by yaw about the z-axis, then by pitch about the new y-axis,
then by roll about the new x-axis. Convention for a mobile robot with x-axis forward
and y-axis sideways.
- ``'xyz'``, rotate by yaw about the x-axis, then by pitch about the new y-axis,
then by roll about the new z-axis. Convention for a robot gripper with z-axis forward
and y-axis between the gripper fingers.
- ``'yxz'``, rotate by yaw about the y-axis, then by pitch about the new x-axis,
then by roll about the new z-axis. Convention for a camera with z-axis parallel
to the optic axis and x-axis parallel to the pixel rows.
If `len(x)` is:
- 1, return an ndarray with shape=(3,)
- N>1, return ndarray with shape=(3,N)
:seealso: :func:`~spatialmath.pose3d.SE3.RPY`, :func:`~spatialmath.base.transforms3d.tr2rpy`
:SymPy: not supported
"""
if len(self) == 1:
return smb.tr2rpy(self.A, unit=unit, order=order) # type: ignore
else:
return np.array([smb.tr2rpy(x, unit=unit, order=order) for x in self.A])
def angvec(self, unit: str = "rad") -> Tuple[float, R3]:
r"""
SO(3) or SE(3) as angle and rotation vector
:param unit: angular units: 'rad' [default], or 'deg'
:type unit: str
:return: :math:`(\theta, \hat{\bf v})`
:rtype: float or ndarray(3)
``x.angvec()`` is a tuple :math:`(\theta, v)` containing the rotation
angle and a rotation axis.
By default the angle is in radians but can be changed setting `unit='deg'`.
.. note::
- If the input is SE(3) the translation component is ignored.
Example:
.. runblock:: pycon
>>> from spatialmath import SO3
>>> R = SO3.Rx(0.3)
>>> R.angvec()
:seealso: :meth:`eulervec` :meth:`AngVec` :meth:`~spatialmath.quaternion.UnitQuaternion.angvec` :meth:`~spatialmath.quaternion.AngVec`, :func:`~angvec2r`
"""
return smb.tr2angvec(self.R, unit=unit)
def eulervec(self) -> R3:
r"""
SO(3) or SE(3) as Euler vector (exponential coordinates)
:return: :math:`\theta \hat{\bf v}`
:rtype: ndarray(3)
``x.eulervec()`` is the Euler vector (or exponential coordinates) which
is related to angle-axis notation and is the product of the rotation
angle and the rotation axis.
Example:
.. runblock:: pycon
>>> from spatialmath import SO3
>>> R = SO3.Rx(0.3)
>>> R.eulervec()
.. note::
- If the input is SE(3) the translation component is ignored.
:seealso: :meth:`angvec` :func:`~angvec2r`
"""
theta, v = smb.tr2angvec(self.R)
return theta * v
# ------------------------------------------------------------------------ #
@staticmethod
def isvalid(x: NDArray, check: bool = True) -> bool:
"""
Test if matrix is valid SO(3)
:param x: matrix to test
:type x: numpy.ndarray
:return: ``True`` if the matrix is a valid element of SO(3), ie. it is a 3x3
orthonormal matrix with determinant of +1.
:rtype: bool
:seealso: :func:`~spatialmath.base.transform3d.isrot`
"""
return smb.isrot(x, check=True)
# ---------------- variant constructors ---------------------------------- #
@classmethod
def Rx(cls, theta: float, unit: str = "rad") -> Self:
"""
Construct a new SO(3) from X-axis rotation
:param θ: rotation angle about the X-axis
:type θ: float or array_like
:param unit: angular units: 'rad' [default], or 'deg'
:type unit: str
:return: SO(3) rotation
:rtype: SO3 instance
- ``SE3.Rx(θ)`` is an SO(3) rotation of ``θ`` radians about the x-axis
- ``SE3.Rx(θ, "deg")`` as above but ``θ`` is in degrees
If ``theta`` is an array then the result is a sequence of rotations defined by consecutive
elements.
Example:
.. runblock:: pycon
>>> from spatialmath import SO3
>>> import numpy as np
>>> x = SO3.Rx(np.linspace(0, math.pi, 20))
>>> len(x)
>>> x[7]
"""
return cls([smb.rotx(x, unit=unit) for x in smb.getvector(theta)], check=False)
@classmethod
def Ry(cls, theta, unit: str = "rad") -> Self:
"""
Construct a new SO(3) from Y-axis rotation
:param θ: rotation angle about Y-axis
:type θ: float or array_like
:param unit: angular units: 'rad' [default], or 'deg'
:type unit: str
:return: SO(3) rotation
:rtype: SO3 instance
- ``SO3.Ry(θ)`` is an SO(3) rotation of ``θ`` radians about the y-axis
- ``SO3.Ry(θ, "deg")`` as above but ``θ`` is in degrees
If ``θ`` is an array then the result is a sequence of rotations defined by consecutive
elements.
Example:
.. runblock:: pycon
>>> from spatialmath import SO3
>>> import numpy as np
>>> x = SO3.Ry(np.linspace(0, math.pi, 20))
>>> len(x)
>>> x[7]
"""
return cls([smb.roty(x, unit=unit) for x in smb.getvector(theta)], check=False)
@classmethod
def Rz(cls, theta, unit: str = "rad") -> Self:
"""
Construct a new SO(3) from Z-axis rotation
:param θ: rotation angle about Z-axis
:type θ: float or array_like
:param unit: angular units: 'rad' [default], or 'deg'
:type unit: str
:return: SO(3) rotation
:rtype: SO3 instance
- ``SO3.Rz(θ)`` is an SO(3) rotation of ``θ`` radians about the z-axis
- ``SO3.Rz(θ, "deg")`` as above but ``θ`` is in degrees
If ``θ`` is an array then the result is a sequence of rotations defined by consecutive
elements.
Example:
.. runblock:: pycon
>>> from spatialmath import SO3
>>> import numpy as np
>>> x = SO3.Rz(np.linspace(0, math.pi, 20))
>>> len(x)
>>> x[7]
"""
return cls([smb.rotz(x, unit=unit) for x in smb.getvector(theta)], check=False)
@classmethod
def Rand(cls, N: int = 1, *, theta_range:Optional[ArrayLike2] = None, unit: str = "rad") -> Self:
"""
Construct a new SO(3) from random rotation
:param N: number of random rotations
:type N: int
:param theta_range: angular magnitude range [min,max], defaults to None.
:type xrange: 2-element sequence, optional
:param unit: angular units: 'rad' [default], or 'deg'
:type unit: str
:return: SO(3) rotation matrix
:rtype: SO3 instance
- ``SO3.Rand()`` is a random SO(3) rotation.
- ``SO3.Rand(N)`` is a sequence of N random rotations.
Example:
.. runblock:: pycon
>>> from spatialmath import SO3
>>> x = SO3.Rand()
>>> x
:seealso: :func:`spatialmath.quaternion.UnitQuaternion.Rand`
"""
return cls([smb.q2r(smb.qrand(theta_range=theta_range, unit=unit)) for _ in range(0, N)], check=False)
@overload
@classmethod
def Eul(cls, *angles: float, unit: str = "rad") -> Self:
...
@overload
@classmethod
def Eul(cls, *angles: Union[ArrayLike3, RNx3], unit: str = "rad") -> Self:
...
@classmethod
def Eul(cls, *angles, unit: str = "rad") -> Self:
r"""
Construct a new SO(3) from Euler angles
:param 𝚪: Euler angles
:type 𝚪: 3 floats, array_like(3) or ndarray(N,3)
:param unit: angular units: 'rad' [default], or 'deg'
:type unit: str
:return: SO(3) rotation
:rtype: SO3 instance
``SO3.Eul(𝚪)`` is an SO(3) rotation defined by a 3-vector of Euler
angles :math:`\Gamma = (\phi, \theta, \psi)` which correspond to
consecutive rotations about the Z, Y, Z axes respectively. If ``𝚪``
is an Nx3 matrix then the result is a sequence of rotations each
defined by Euler angles corresponding to the rows of ``angles``.
``SO3.Eul(φ, θ, ψ)`` as above but the angles are provided as three
scalars.
Example:
.. runblock:: pycon
>>> from spatialmath import SO3
>>> SO3.Eul(0.1, 0.2, 0.3)
>>> SO3.Eul([0.1, 0.2, 0.3])
>>> SO3.Eul(10, 20, 30, unit="deg")
:seealso: :func:`~spatialmath.pose3d.SE3.eul`, :func:`~spatialmath.pose3d.SE3.Eul`, :func:`~spatialmath.base.transforms3d.eul2r`
"""
if len(angles) == 1:
angles = angles[0]
if smb.isvector(angles, 3):
return cls(smb.eul2r(angles, unit=unit), check=False)
else:
return cls([smb.eul2r(a, unit=unit) for a in angles], check=False)
@overload
@classmethod
def RPY(
cls,
*angles: float,
unit: str = "rad",
order="zyx",
) -> Self:
...
@overload
@classmethod
def RPY(
cls, *angles: Union[ArrayLike3, RNx3], unit: str = "rad", order="zyx"
) -> Self:
...
@classmethod
def RPY(cls, *angles, unit="rad", order="zyx"):
r"""
Construct a new SO(3) from roll-pitch-yaw angles
:param angles: roll-pitch-yaw angles
:type angles: array_like(3), array_like(n,3)
:param unit: angular units: 'rad' [default], or 'deg'
:type unit: str
:param order: rotation order: 'zyx' [default], 'xyz', or 'yxz'
:type order: str
:return: SO(3) rotation
:rtype: SO3 instance
- ``SO3.RPY(angles)`` is an SO(3) rotation defined by a 3-vector of
roll, pitch, yaw angles :math:`(\alpha, \beta, \gamma)`. If ``angles``
is an Nx3 matrix then the result is a sequence of rotations each
defined by RPY angles corresponding to the rows of angles. The angles
correspond to successive rotations about the axes specified by
``order``:
- ``'zyx'`` [default], rotate by yaw about the z-axis, then by pitch about the new y-axis,
then by roll about the new x-axis. Convention for a mobile robot with x-axis forward
and y-axis sideways.
- ``'xyz'``, rotate by yaw about the x-axis, then by pitch about the new y-axis,
then by roll about the new z-axis. Convention for a robot gripper with z-axis forward
and y-axis between the gripper fingers.
- ``'yxz'``, rotate by yaw about the y-axis, then by pitch about the new x-axis,
then by roll about the new z-axis. Convention for a camera with z-axis parallel
to the optic axis and x-axis parallel to the pixel rows.
- ``SO3.RPY(⍺, β, 𝛾)`` as above but the angles are provided as three
scalars.
Example:
.. runblock:: pycon
>>> from spatialmath import SO3
>>> SO3.RPY(0.1, 0.2, 0.3)
>>> SO3.RPY([0.1, 0.2, 0.3])
>>> SO3.RPY(0.1, 0.2, 0.3, order='xyz')
>>> SO3.RPY(10, 20, 30, unit="deg")
:seealso: :func:`~spatialmath.pose3d.SE3.rpy`, :func:`~spatialmath.pose3d.SE3.RPY`, :func:`spatialmath.base.transforms3d.rpy2r`
"""
if len(angles) == 1:
angles = angles[0]
# angles = base.getmatrix(angles, (None, 3))
# return cls(base.rpy2r(angles, order=order, unit=unit), check=False)
if smb.isvector(angles, 3):
return cls(smb.rpy2r(angles, unit=unit, order=order), check=False)
else:
return cls(
[smb.rpy2r(a, unit=unit, order=order) for a in angles], check=False
)
@classmethod
def OA(cls, o: ArrayLike3, a: ArrayLike3) -> Self:
"""
Construct a new SO(3) from two vectors
:param o: 3-vector parallel to Y- axis
:type o: array_like
:param a: 3-vector parallel to the Z-axis
:type o: array_like
:return: SO(3) rotation
:rtype: SO3 instance
``SO3.OA(O, A)`` is an SO(3) rotation defined in terms of
vectors parallel to the Y- and Z-axes of its reference frame. In robotics these axes are
respectively called the *orientation* and *approach* vectors defined such that
R = [N, O, A] and N = O x A.
.. note::
- Only the ``A`` vector is guaranteed to have the same direction in the resulting
rotation matrix
- ``O`` and ``A`` do not have to be unit-length, they are normalized
- ``O`` and ``A` do not have to be orthogonal, so long as they are not parallel
:seealso: :func:`spatialmath.base.transforms3d.oa2r`
"""
return cls(smb.oa2r(o, a), check=False)
@classmethod
def TwoVectors(
cls,
x: Optional[Union[str, ArrayLike3]] = None,
y: Optional[Union[str, ArrayLike3]] = None,
z: Optional[Union[str, ArrayLike3]] = None,
) -> Self:
"""
Construct a new SO(3) from any two vectors
:param x: new x-axis, defaults to None
:type x: str, array_like(3), optional
:param y: new y-axis, defaults to None
:type y: str, array_like(3), optional
:param z: new z-axis, defaults to None
:type z: str, array_like(3), optional
Create a rotation by defining the direction of two of the new
axes in terms of the old axes. Axes are denoted by strings ``"x"``,
``"y"``, ``"z"``, ``"-x"``, ``"-y"``, ``"-z"``.
The directions can also be specified by 3-element vectors. If the vectors are not orthogonal,
they will orthogonalized w.r.t. the first available dimension. I.e. if x is available, it will be
normalized and the remaining vector will be orthogonalized w.r.t. x, else, y will be normalized
and z will be orthogonalized w.r.t. y.
To create a rotation where the new frame has its x-axis in -z-direction
of the previous frame, and its z-axis in the x-direction of the previous
frame is::
>>> SO3.TwoVectors(x='-z', z='x')
"""
def vval(v):
if isinstance(v, str):
sign = 1
if v[0] == "-":
sign = -1
v = v[1:] # skip sign char
elif v[0] == "+":
v = v[1:] # skip sign char
if v[0] == "x":
v = [sign, 0, 0]
elif v[0] == "y":
v = [0, sign, 0]
elif v[0] == "z":
v = [0, 0, sign]
return np.r_[v]
else:
return smb.unitvec(smb.getvector(v, 3))
if x is not None and y is not None and z is not None:
raise ValueError(
"Only two vectors should be provided. Please set one to None."
)
elif x is not None and y is not None and z is None:
# z = x x y
x = vval(x)
y = vval(y)
# Orthogonalizes y w.r.t. x
y = orthogonalize(y, x, normalize=True)
z = np.cross(x, y)
elif x is None and y is not None and z is not None:
# x = y x z
y = vval(y)
z = vval(z)
# Orthogonalizes z w.r.t. y
z = orthogonalize(z, y, normalize=True)
x = np.cross(y, z)
elif x is not None and y is None and z is not None:
# y = z x x
z = vval(z)
x = vval(x)
# Orthogonalizes z w.r.t. x
z = orthogonalize(z, x, normalize=True)
y = np.cross(z, x)
else:
raise ValueError(
"Insufficient number of vectors. Please provide exactly two vectors."
)
return cls(np.c_[x, y, z], check=True)
@classmethod
def RotatedVector(cls, v1: ArrayLike3, v2: ArrayLike3, tol=20) -> Self:
"""
Construct a new SO(3) from a vector and its rotated image
:param v1: initial vector
:type v1: array_like(3)
:param v2: vector after rotation
:type v2: array_like(3)
:param tol: tolerance for singularity in units of eps, defaults to 20
:type tol: float
:return: SO(3) rotation
:rtype: :class:`SO3` instance
``SO3.RotatedVector(v1, v2)`` is an SO(3) rotation defined in terms of
two vectors. The rotation takes vector ``v1`` to ``v2``.
.. runblock:: pycon
>>> from spatialmath import SO3
>>> v1 = [1, 2, 3]
>>> v2 = SO3.Eul(0.3, 0.4, 0.5) * v1
>>> print(v2)
>>> R = SO3.RotatedVector(v1, v2)
>>> print(R)
>>> print(R * v1)
.. note:: The vectors do not have to be unit-length.
"""
# https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d
v1 = smb.unitvec(v1)
v2 = smb.unitvec(v2)
v = smb.cross(v1, v2)
s = smb.norm(v)
if abs(s) < tol * np.finfo(float).eps:
return cls(np.eye(3), check=False)
else:
c = np.dot(v1, v2)
V = smb.skew(v)
R = np.eye(3) + V + V @ V * (1 - c) / (s**2)
return cls(R, check=False)
@classmethod
def AngleAxis(cls, theta: float, v: ArrayLike3, *, unit: str = "rad") -> Self:
r"""
Construct a new SO(3) rotation matrix from rotation angle and axis
:param theta: rotation
:type theta: float
:param unit: angular units: 'rad' [default], or 'deg'
:type unit: str
:param v: rotation axis, 3-vector
:type v: array_like
:return: SO(3) rotation
:rtype: SO3 instance
``SO3.AngleAxis(theta, V)`` is an SO(3) rotation defined by
a rotation of ``THETA`` about the vector ``V``.
.. note:: :math:`\theta \eq 0` the result in an identity matrix, otherwise
``V`` must have a finite length, ie. :math:`|V| > 0`.
:seealso: :func:`~spatialmath.pose3d.SE3.angvec`, :func:`spatialmath.base.transforms3d.angvec2r`
"""
return cls(smb.angvec2r(theta, v, unit=unit), check=False)
@classmethod
def AngVec(cls, theta, v, *, unit="rad") -> Self:
r"""
Construct a new SO(3) rotation matrix from rotation angle and axis
:param theta: rotation
:type theta: float
:param unit: angular units: 'rad' [default], or 'deg'
:type unit: str
:param v: rotation axis, 3-vector
:type v: array_like
:return: SO(3) rotation
:rtype: SO3 instance
``SO3.AngVec(theta, V)`` is an SO(3) rotation defined by
a rotation of ``THETA`` about the vector ``V``.
.. deprecated:: 0.9.8
Use :meth:`AngleAxis` instead.
:seealso: :func:`~spatialmath.pose3d.SE3.angvec`, :func:`spatialmath.base.transforms3d.angvec2r`
"""
return cls(smb.angvec2r(theta, v, unit=unit), check=False)
@classmethod
def EulerVec(cls, w) -> Self:
r"""
Construct a new SO(3) rotation matrix from an Euler rotation vector
:param ω: rotation axis
:type ω: 3-element array_like
:return: SO(3) rotation
:rtype: SO3 instance
``SO3.EulerVec(ω)`` is a unit quaternion that describes the 3D rotation
defined by a rotation of :math:`\theta = \lVert \omega \rVert` about the
unit 3-vector :math:`\omega / \lVert \omega \rVert`.
Example:
.. runblock:: pycon
>>> from spatialmath import SO3
>>> SO3.EulerVec([0.5,0,0])
.. note:: :math:`\theta \eq 0` the result in an identity matrix, otherwise
``V`` must have a finite length, ie. :math:`|V| > 0`.
:seealso: :func:`~spatialmath.pose3d.SE3.angvec`, :func:`~spatialmath.base.transforms3d.angvec2r`
"""
assert smb.isvector(w, 3), "w must be a 3-vector"
w = smb.getvector(w)
theta = smb.norm(w)
return cls(smb.angvec2r(theta, w), check=False)
@classmethod
def Exp(
cls,
S: Union[R3, RNx3],
check: bool = True,
so3: bool = True,
) -> Self:
r"""
Create an SO(3) rotation matrix from so(3)
:param S: Lie algebra so(3)
:type S: ndarray(3,3), ndarray(n,3)
:param check: check that passed matrix is valid so(3), default True
:bool check: bool, optional
:param so3: the input is interpretted as an so(3) matrix not a stack of three twists, default True
:return: SO(3) rotation
:rtype: SO3 instance
- ``SO3.Exp(S)`` is an SO(3) rotation defined by its Lie algebra
which is a 3x3 so(3) matrix (skew symmetric)
- ``SO3.Exp(t)`` is an SO(3) rotation defined by a 3-element twist
vector (the unique elements of the so(3) skew-symmetric matrix)
- ``SO3.Exp(T)`` is a sequence of SO(3) rotations defined by an Nx3 matrix
of twist vectors, one per row.
.. note::
- if :math:`\theta \eq 0` the result in an identity matrix
- an input 3x3 matrix is ambiguous, it could be the first or third case above. In this
case the parameter `so3` is the decider.
:seealso: :func:`spatialmath.base.transforms3d.trexp`, :func:`spatialmath.base.transformsNd.skew`
"""
if smb.ismatrix(S, (-1, 3)) and not so3:
return cls([smb.trexp(s, check=check) for s in S], check=False)
else:
return cls(smb.trexp(cast(R3, S), check=check), check=False)
def UnitQuaternion(self) -> UnitQuaternion:
"""
SO3 as a unit quaternion instance
:return: a unit quaternion representation
:rtype: UnitQuaternion instance
``R.UnitQuaternion()`` is an ``UnitQuaternion`` instance representing the same rotation
as the SO3 rotation ``R``.
Example:
.. runblock:: pycon
>>> from spatialmath import SO3
>>> SO3.Rz(0.3).UnitQuaternion()
"""
# Function level import to avoid circular dependencies
from spatialmath import UnitQuaternion
return UnitQuaternion(smb.r2q(self.R), check=False)
def angdist(self, other: SO3, metric: int = 6) -> Union[float, ndarray]:
r"""
Angular distance metric between rotations
:param other: second rotation
:type other: SO3 instance
:param metric: metric, default is 6
:type metric: int
:raises TypeError: if other is not an SO3
:return: angle in radians
:rtype: float or ndarray
``R1.angdist(R2)`` is the geodesic norm, or geodesic distance between two
rotations.
Several metrics are supported, the first 5 are computed after conversion
to unit quaternions.
====== ===============================================================
Metric Details
====== ===============================================================
0 :math:`1 - | \q_1 \bullet \q_2 | \in [0, 1]`
1 :math:`\cos^{-1} | \q_1 \bullet \q_2 | \in [0, \pi/2]`
2 :math:`\cos^{-1} | \q_1 \bullet \q_2 | \in [0, \pi/2]`
3 :math:`2 \tan^{-1} \| \q_1 - \q_2\| / \|\q_1 + \q_2\| \in [0, \pi/2]`
4 :math:`\cos^{-1} \left( 2 (\q_1 \bullet \q_2)^2 - 1\right) \in [0, 1]`
5 :math:`\|I - \mat{R}_1 \mat{R}_2^T\| \in [0, 2]`
6 :math:`\|\log \mat{R}_1 \mat{R}_2^T\| \in [0, \pi]`
====== ===============================================================
Example:
.. runblock:: pycon
>>> from spatialmath import SO3
>>> R1 = SO3.Rx(0.3)
>>> R2 = SO3.Ry(0.3)
>>> print(R1.angdist(R1))
>>> print(R1.angdist(R2))
.. note::
- metrics 1, 2, 4 can throw ValueError "math domain error" due to
numeric errors which push the argument of ``acos()`` marginally
outside its domain [0, 1].
- metrics 2 and 3 are equivalent, but 3 is more robust
:seealso: :func:`UnitQuaternion.angdist`
"""
if metric < 5:
from spatialmath.quaternion import UnitQuaternion
return UnitQuaternion(self).angdist(UnitQuaternion(other), metric=metric)
elif metric == 5:
op = lambda R1, R2: np.linalg.norm(np.eye(3) - R1 @ R2.T)
elif metric == 6:
op = lambda R1, R2: smb.norm(smb.trlog(R1 @ R2.T, twist=True))
else:
raise ValueError("unknown metric")
ad = self._op2(other, op)
if isinstance(ad, list):
return np.array(ad)
else:
return ad
def mean(self, tol: float = 20) -> SO3:
"""Mean of a set of rotations
:param tol: iteration tolerance in units of eps, defaults to 20
:type tol: float, optional
:return: the mean rotation
:rtype: :class:`SO3` instance.
Computes the Karcher mean of the set of rotations within the SO(3) instance.
:references:
- `**Hartley, Trumpf** - "Rotation Averaging" - IJCV 2011 <https://users.cecs.anu.edu.au/~hartley/Papers/PDF/Hartley-Trumpf:Rotation-averaging:IJCV.pdf>`_, Algorithm 1, page 15.
- `Karcher mean <https://en.wikipedia.org/wiki/Karcher_mean>`_
"""
eta = tol * np.finfo(float).eps
R_mean = self[0] # initial guess
while True:
r = np.dstack((R_mean.inv() * self).log()).mean(axis=2)
if np.linalg.norm(r) < eta:
return R_mean
R_mean = R_mean @ self.Exp(r) # update estimate and normalize
# ============================== SE3 =====================================#