-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
rotation.pyx
2451 lines (1982 loc) · 83.2 KB
/
rotation.pyx
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
import re
import warnings
import numpy as np
from scipy._lib._util import check_random_state
from ._rotation_groups import create_group
cimport numpy as np
cimport cython
from cython.view cimport array
from libc.math cimport sqrt, sin, cos, atan2, acos
from numpy.math cimport PI as pi, NAN, isnan # avoid MSVC error
# utilities for empty array initialization
cdef inline double[:] _empty1(int n):
return array(shape=(n,), itemsize=sizeof(double), format=b"d")
cdef inline double[:, :] _empty2(int n1, int n2):
return array(shape=(n1, n2), itemsize=sizeof(double), format=b"d")
cdef inline double[:, :, :] _empty3(int n1, int n2, int n3):
return array(shape=(n1, n2, n3), itemsize=sizeof(double), format=b"d")
cdef inline double[:, :] _zeros2(int n1, int n2):
cdef double[:, :] arr = array(shape=(n1, n2),
itemsize=sizeof(double), format=b"d")
arr[:, :] = 0
return arr
# flat implementations of numpy functions
@cython.boundscheck(False)
@cython.wraparound(False)
cdef inline double[:] _cross3(const double[:] a, const double[:] b):
cdef double[:] result = _empty1(3)
result[0] = a[1]*b[2] - a[2]*b[1]
result[1] = a[2]*b[0] - a[0]*b[2]
result[2] = a[0]*b[1] - a[1]*b[0]
return result
@cython.boundscheck(False)
@cython.wraparound(False)
cdef inline double _dot3(const double[:] a, const double[:] b) nogil:
return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
@cython.boundscheck(False)
@cython.wraparound(False)
cdef inline double _norm3(const double[:] elems) nogil:
return sqrt(_dot3(elems, elems))
@cython.boundscheck(False)
@cython.wraparound(False)
cdef inline double _normalize4(double[:] elems) nogil:
cdef double norm = sqrt(_dot3(elems, elems) + elems[3]*elems[3])
if norm == 0:
return NAN
elems[0] /= norm
elems[1] /= norm
elems[2] /= norm
elems[3] /= norm
return norm
@cython.boundscheck(False)
@cython.wraparound(False)
cdef inline int _argmax4(double[:] a) nogil:
cdef int imax = 0
cdef double vmax = a[0]
for i in range(1, 4):
if a[i] > vmax:
imax = i
vmax = a[i]
return imax
ctypedef unsigned char uchar
cdef double[3] _ex = [1, 0, 0]
cdef double[3] _ey = [0, 1, 0]
cdef double[3] _ez = [0, 0, 1]
@cython.boundscheck(False)
@cython.wraparound(False)
cdef inline const double[:] _elementary_basis_vector(uchar axis):
if axis == b'x': return _ex
elif axis == b'y': return _ey
elif axis == b'z': return _ez
@cython.boundscheck(False)
@cython.wraparound(False)
cdef double[:, :] _compute_euler_from_matrix(
np.ndarray[double, ndim=3] matrix, const uchar[:] seq, bint extrinsic=False
):
# The algorithm assumes intrinsic frame transformations. The algorithm
# in the paper is formulated for rotation matrices which are transposition
# rotation matrices used within Rotation.
# Adapt the algorithm for our case by
# 1. Instead of transposing our representation, use the transpose of the
# O matrix as defined in the paper, and be careful to swap indices
# 2. Reversing both axis sequence and angles for extrinsic rotations
if extrinsic:
seq = seq[::-1]
cdef Py_ssize_t num_rotations = matrix.shape[0]
# Step 0
# Algorithm assumes axes as column vectors, here we use 1D vectors
cdef const double[:] n1 = _elementary_basis_vector(seq[0])
cdef const double[:] n2 = _elementary_basis_vector(seq[1])
cdef const double[:] n3 = _elementary_basis_vector(seq[2])
# Step 2
cdef double sl = _dot3(_cross3(n1, n2), n3)
cdef double cl = _dot3(n1, n3)
# angle offset is lambda from the paper referenced in [2] from docstring of
# `as_euler` function
cdef double offset = atan2(sl, cl)
cdef double[:, :] c_ = _empty2(3, 3)
c_[0, :] = n2
c_[1, :] = _cross3(n1, n2)
c_[2, :] = n1
cdef np.ndarray[double, ndim=2] c = np.asarray(c_)
rot = np.array([
[1, 0, 0],
[0, cl, sl],
[0, -sl, cl],
])
# some forward definitions
cdef double[:, :] angles = _empty2(num_rotations, 3)
cdef double[:, :] matrix_trans # transformed matrix
cdef double[:] _angles # accessor for each rotation
cdef np.ndarray[double, ndim=2] res
cdef double eps = 1e-7
cdef bint safe1, safe2, safe, adjust
for ind in range(num_rotations):
_angles = angles[ind, :]
# Step 3
res = np.dot(c, matrix[ind, :, :])
matrix_trans = np.dot(res, c.T.dot(rot))
# Step 4
# Ensure less than unit norm
matrix_trans[2, 2] = min(matrix_trans[2, 2], 1)
matrix_trans[2, 2] = max(matrix_trans[2, 2], -1)
_angles[1] = acos(matrix_trans[2, 2])
# Steps 5, 6
safe1 = abs(_angles[1]) >= eps
safe2 = abs(_angles[1] - <double>pi) >= eps
safe = safe1 and safe2
# Step 4 (Completion)
_angles[1] += offset
# 5b
if safe:
_angles[0] = atan2(matrix_trans[0, 2], -matrix_trans[1, 2])
_angles[2] = atan2(matrix_trans[2, 0], matrix_trans[2, 1])
if extrinsic:
# For extrinsic, set first angle to zero so that after reversal we
# ensure that third angle is zero
# 6a
if not safe:
_angles[0] = 0
# 6b
if not safe1:
_angles[2] = atan2(matrix_trans[1, 0] - matrix_trans[0, 1],
matrix_trans[0, 0] + matrix_trans[1, 1])
# 6c
if not safe2:
_angles[2] = -atan2(matrix_trans[1, 0] + matrix_trans[0, 1],
matrix_trans[0, 0] - matrix_trans[1, 1])
else:
# For instrinsic, set third angle to zero
# 6a
if not safe:
_angles[2] = 0
# 6b
if not safe1:
_angles[0] = atan2(matrix_trans[1, 0] - matrix_trans[0, 1],
matrix_trans[0, 0] + matrix_trans[1, 1])
# 6c
if not safe2:
_angles[0] = atan2(matrix_trans[1, 0] + matrix_trans[0, 1],
matrix_trans[0, 0] - matrix_trans[1, 1])
# Step 7
if seq[0] == seq[2]:
# lambda = 0, so we can only ensure angle2 -> [0, pi]
adjust = _angles[1] < 0 or _angles[1] > pi
else:
# lambda = + or - pi/2, so we can ensure angle2 -> [-pi/2, pi/2]
adjust = _angles[1] < -pi / 2 or _angles[1] > pi / 2
# Dont adjust gimbal locked angle sequences
if adjust and safe:
_angles[0] += pi
_angles[1] = 2 * offset - _angles[1]
_angles[2] -= pi
for i in range(3):
if _angles[i] < -pi:
_angles[i] += 2 * pi
elif _angles[i] > pi:
_angles[i] -= 2 * pi
# Step 8
if not safe:
warnings.warn("Gimbal lock detected. Setting third angle to zero "
"since it is not possible to uniquely determine "
"all angles.")
# Reverse role of extrinsic and intrinsic rotations, but let third angle be
# zero for gimbal locked cases. Take a copy, to enforce contiguous memory layout.
if extrinsic:
angles = angles[:, ::-1].copy()
return angles
@cython.boundscheck(False)
@cython.wraparound(False)
cdef inline void _compose_quat_single( # calculate p * q into r
const double[:] p, const double[:] q, double[:] r
):
cdef double[:] cross = _cross3(p[:3], q[:3])
r[0] = p[3]*q[0] + q[3]*p[0] + cross[0]
r[1] = p[3]*q[1] + q[3]*p[1] + cross[1]
r[2] = p[3]*q[2] + q[3]*p[2] + cross[2]
r[3] = p[3]*q[3] - p[0]*q[0] - p[1]*q[1] - p[2]*q[2]
@cython.boundscheck(False)
@cython.wraparound(False)
cdef inline double[:, :] _compose_quat(
const double[:, :] p, const double[:, :] q
):
cdef Py_ssize_t n = max(p.shape[0], q.shape[0])
cdef double[:, :] product = _empty2(n, 4)
# dealing with broadcasting
if p.shape[0] == 1:
for ind in range(n):
_compose_quat_single(p[0], q[ind], product[ind])
elif q.shape[0] == 1:
for ind in range(n):
_compose_quat_single(p[ind], q[0], product[ind])
else:
for ind in range(n):
_compose_quat_single(p[ind], q[ind], product[ind])
return product
@cython.boundscheck(False)
@cython.wraparound(False)
cdef inline double[:, :] _make_elementary_quat(
uchar axis, const double[:] angles
):
cdef Py_ssize_t n = angles.shape[0]
cdef double[:, :] quat = _zeros2(n, 4)
cdef int axis_ind
if axis == b'x': axis_ind = 0
elif axis == b'y': axis_ind = 1
elif axis == b'z': axis_ind = 2
for ind in range(n):
quat[ind, 3] = cos(angles[ind] / 2)
quat[ind, axis_ind] = sin(angles[ind] / 2)
return quat
@cython.boundscheck(False)
@cython.wraparound(False)
cdef double[:, :] _elementary_quat_compose(
const uchar[:] seq, const double[:, :] angles, bint intrinsic=False
):
cdef double[:, :] result = _make_elementary_quat(seq[0], angles[:, 0])
cdef Py_ssize_t seq_len = seq.shape[0]
for idx in range(1, seq_len):
if intrinsic:
result = _compose_quat(
result,
_make_elementary_quat(seq[idx], angles[:, idx]))
else:
result = _compose_quat(
_make_elementary_quat(seq[idx], angles[:, idx]),
result)
return result
cdef class Rotation(object):
"""Rotation in 3 dimensions.
This class provides an interface to initialize from and represent rotations
with:
- Quaternions
- Rotation Matrices
- Rotation Vectors
- Modified Rodrigues Parameters
- Euler Angles
The following operations on rotations are supported:
- Application on vectors
- Rotation Composition
- Rotation Inversion
- Rotation Indexing
Indexing within a rotation is supported since multiple rotation transforms
can be stored within a single `Rotation` instance.
To create `Rotation` objects use ``from_...`` methods (see examples below).
``Rotation(...)`` is not supposed to be instantiated directly.
Attributes
----------
single
Methods
-------
__len__
from_quat
from_matrix
from_rotvec
from_mrp
from_euler
as_quat
as_matrix
as_rotvec
as_mrp
as_euler
apply
__mul__
inv
magnitude
mean
reduce
create_group
__getitem__
identity
random
align_vectors
See Also
--------
Slerp
Notes
-----
.. versionadded: 1.2.0
Examples
--------
>>> from scipy.spatial.transform import Rotation as R
A `Rotation` instance can be initialized in any of the above formats and
converted to any of the others. The underlying object is independent of the
representation used for initialization.
Consider a counter-clockwise rotation of 90 degrees about the z-axis. This
corresponds to the following quaternion (in scalar-last format):
>>> r = R.from_quat([0, 0, np.sin(np.pi/4), np.cos(np.pi/4)])
The rotation can be expressed in any of the other formats:
>>> r.as_matrix()
array([[ 2.22044605e-16, -1.00000000e+00, 0.00000000e+00],
[ 1.00000000e+00, 2.22044605e-16, 0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]])
>>> r.as_rotvec()
array([0. , 0. , 1.57079633])
>>> r.as_euler('zyx', degrees=True)
array([90., 0., 0.])
The same rotation can be initialized using a rotation matrix:
>>> r = R.from_matrix([[0, -1, 0],
... [1, 0, 0],
... [0, 0, 1]])
Representation in other formats:
>>> r.as_quat()
array([0. , 0. , 0.70710678, 0.70710678])
>>> r.as_rotvec()
array([0. , 0. , 1.57079633])
>>> r.as_euler('zyx', degrees=True)
array([90., 0., 0.])
The rotation vector corresponding to this rotation is given by:
>>> r = R.from_rotvec(np.pi/2 * np.array([0, 0, 1]))
Representation in other formats:
>>> r.as_quat()
array([0. , 0. , 0.70710678, 0.70710678])
>>> r.as_matrix()
array([[ 2.22044605e-16, -1.00000000e+00, 0.00000000e+00],
[ 1.00000000e+00, 2.22044605e-16, 0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]])
>>> r.as_euler('zyx', degrees=True)
array([90., 0., 0.])
The ``from_euler`` method is quite flexible in the range of input formats
it supports. Here we initialize a single rotation about a single axis:
>>> r = R.from_euler('z', 90, degrees=True)
Again, the object is representation independent and can be converted to any
other format:
>>> r.as_quat()
array([0. , 0. , 0.70710678, 0.70710678])
>>> r.as_matrix()
array([[ 2.22044605e-16, -1.00000000e+00, 0.00000000e+00],
[ 1.00000000e+00, 2.22044605e-16, 0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]])
>>> r.as_rotvec()
array([0. , 0. , 1.57079633])
It is also possible to initialize multiple rotations in a single instance
using any of the `from_...` functions. Here we initialize a stack of 3
rotations using the ``from_euler`` method:
>>> r = R.from_euler('zyx', [
... [90, 0, 0],
... [0, 45, 0],
... [45, 60, 30]], degrees=True)
The other representations also now return a stack of 3 rotations. For
example:
>>> r.as_quat()
array([[0. , 0. , 0.70710678, 0.70710678],
[0. , 0.38268343, 0. , 0.92387953],
[0.39190384, 0.36042341, 0.43967974, 0.72331741]])
Applying the above rotations onto a vector:
>>> v = [1, 2, 3]
>>> r.apply(v)
array([[-2. , 1. , 3. ],
[ 2.82842712, 2. , 1.41421356],
[ 2.24452282, 0.78093109, 2.89002836]])
A `Rotation` instance can be indexed and sliced as if it were a single
1D array or list:
>>> r.as_quat()
array([[0. , 0. , 0.70710678, 0.70710678],
[0. , 0.38268343, 0. , 0.92387953],
[0.39190384, 0.36042341, 0.43967974, 0.72331741]])
>>> p = r[0]
>>> p.as_matrix()
array([[ 2.22044605e-16, -1.00000000e+00, 0.00000000e+00],
[ 1.00000000e+00, 2.22044605e-16, 0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]])
>>> q = r[1:3]
>>> q.as_quat()
array([[0. , 0.38268343, 0. , 0.92387953],
[0.39190384, 0.36042341, 0.43967974, 0.72331741]])
In fact it can be converted to numpy.array:
>>> r_array = np.asarray(r)
>>> r_array.shape
(3,)
>>> r_array[0].as_matrix()
array([[ 2.22044605e-16, -1.00000000e+00, 0.00000000e+00],
[ 1.00000000e+00, 2.22044605e-16, 0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]])
Multiple rotations can be composed using the ``*`` operator:
>>> r1 = R.from_euler('z', 90, degrees=True)
>>> r2 = R.from_rotvec([np.pi/4, 0, 0])
>>> v = [1, 2, 3]
>>> r2.apply(r1.apply(v))
array([-2. , -1.41421356, 2.82842712])
>>> r3 = r2 * r1 # Note the order
>>> r3.apply(v)
array([-2. , -1.41421356, 2.82842712])
Finally, it is also possible to invert rotations:
>>> r1 = R.from_euler('z', [90, 45], degrees=True)
>>> r2 = r1.inv()
>>> r2.as_euler('zyx', degrees=True)
array([[-90., 0., 0.],
[-45., 0., 0.]])
These examples serve as an overview into the `Rotation` class and highlight
major functionalities. For more thorough examples of the range of input and
output formats supported, consult the individual method's examples.
"""
cdef double[:, :] _quat
cdef bint _single
@cython.boundscheck(False)
@cython.wraparound(False)
def __init__(self, quat, normalize=True, copy=True):
self._single = False
quat = np.asarray(quat, dtype=float)
if quat.ndim not in [1, 2] or quat.shape[len(quat.shape) - 1] != 4:
raise ValueError("Expected `quat` to have shape (4,) or (N x 4), "
"got {}.".format(quat.shape))
# If a single quaternion is given, convert it to a 2D 1 x 4 matrix but
# set self._single to True so that we can return appropriate objects
# in the `to_...` methods
if quat.shape == (4,):
quat = quat[None, :]
self._single = True
cdef Py_ssize_t num_rotations = quat.shape[0]
if normalize:
self._quat = quat.copy()
for ind in range(num_rotations):
if isnan(_normalize4(self._quat[ind, :])):
raise ValueError("Found zero norm quaternions in `quat`.")
else:
self._quat = quat.copy() if copy else quat
def __getstate__(self):
return np.asarray(self._quat, dtype=float), self._single
def __setstate__(self, state):
quat, single = state
self._quat = quat.copy()
self._single = single
@property
def single(self):
"""Whether this instance represents a single rotation."""
return self._single
def __len__(self):
"""Number of rotations contained in this object.
Multiple rotations can be stored in a single instance.
Returns
-------
length : int
Number of rotations stored in object.
Raises
------
TypeError if the instance was created as a single rotation.
"""
if self._single:
raise TypeError("Single rotation has no len().")
return self._quat.shape[0]
@classmethod
def from_quat(cls, quat):
"""Initialize from quaternions.
3D rotations can be represented using unit-norm quaternions [1]_.
Parameters
----------
quat : array_like, shape (N, 4) or (4,)
Each row is a (possibly non-unit norm) quaternion in scalar-last
(x, y, z, w) format. Each quaternion will be normalized to unit
norm.
Returns
-------
rotation : `Rotation` instance
Object containing the rotations represented by input quaternions.
References
----------
.. [1] https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation
Examples
--------
>>> from scipy.spatial.transform import Rotation as R
Initialize a single rotation:
>>> r = R.from_quat([1, 0, 0, 0])
>>> r.as_quat()
array([1., 0., 0., 0.])
>>> r.as_quat().shape
(4,)
Initialize multiple rotations in a single object:
>>> r = R.from_quat([
... [1, 0, 0, 0],
... [0, 0, 0, 1]
... ])
>>> r.as_quat()
array([[1., 0., 0., 0.],
[0., 0., 0., 1.]])
>>> r.as_quat().shape
(2, 4)
It is also possible to have a stack of a single rotation:
>>> r = R.from_quat([[0, 0, 0, 1]])
>>> r.as_quat()
array([[0., 0., 0., 1.]])
>>> r.as_quat().shape
(1, 4)
Quaternions are normalized before initialization.
>>> r = R.from_quat([0, 0, 1, 1])
>>> r.as_quat()
array([0. , 0. , 0.70710678, 0.70710678])
"""
return cls(quat, normalize=True)
@classmethod
@cython.boundscheck(False)
@cython.wraparound(False)
def from_matrix(cls, matrix):
"""Initialize from rotation matrix.
Rotations in 3 dimensions can be represented with 3 x 3 proper
orthogonal matrices [1]_. If the input is not proper orthogonal,
an approximation is created using the method described in [2]_.
Parameters
----------
matrix : array_like, shape (N, 3, 3) or (3, 3)
A single matrix or a stack of matrices, where ``matrix[i]`` is
the i-th matrix.
Returns
-------
rotation : `Rotation` instance
Object containing the rotations represented by the rotation
matrices.
References
----------
.. [1] https://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions
.. [2] F. Landis Markley, "Unit Quaternion from Rotation Matrix",
Journal of guidance, control, and dynamics vol. 31.2, pp.
440-442, 2008.
Examples
--------
>>> from scipy.spatial.transform import Rotation as R
Initialize a single rotation:
>>> r = R.from_matrix([
... [0, -1, 0],
... [1, 0, 0],
... [0, 0, 1]])
>>> r.as_matrix().shape
(3, 3)
Initialize multiple rotations in a single object:
>>> r = R.from_matrix([
... [
... [0, -1, 0],
... [1, 0, 0],
... [0, 0, 1],
... ],
... [
... [1, 0, 0],
... [0, 0, -1],
... [0, 1, 0],
... ]])
>>> r.as_matrix().shape
(2, 3, 3)
If input matrices are not special orthogonal (orthogonal with
determinant equal to +1), then a special orthogonal estimate is stored:
>>> a = np.array([
... [0, -0.5, 0],
... [0.5, 0, 0],
... [0, 0, 0.5]])
>>> np.linalg.det(a)
0.12500000000000003
>>> r = R.from_matrix(a)
>>> matrix = r.as_matrix()
>>> matrix
array([[-0.38461538, -0.92307692, 0. ],
[ 0.92307692, -0.38461538, 0. ],
[ 0. , 0. , 1. ]])
>>> np.linalg.det(matrix)
1.0000000000000002
It is also possible to have a stack containing a single rotation:
>>> r = R.from_matrix([[
... [0, -1, 0],
... [1, 0, 0],
... [0, 0, 1]]])
>>> r.as_matrix()
array([[[ 0., -1., 0.],
[ 1., 0., 0.],
[ 0., 0., 1.]]])
>>> r.as_matrix().shape
(1, 3, 3)
Notes
-----
This function was called from_dcm before.
.. versionadded:: 1.4.0
"""
is_single = False
matrix = np.asarray(matrix, dtype=float)
if (matrix.ndim not in [2, 3] or
matrix.shape[len(matrix.shape)-2:] != (3, 3)):
raise ValueError("Expected `matrix` to have shape (3, 3) or "
"(N, 3, 3), got {}".format(matrix.shape))
# If a single matrix is given, convert it to 3D 1 x 3 x 3 matrix but
# set self._single to True so that we can return appropriate objects in
# the `to_...` methods
cdef double[:, :, :] cmatrix
if matrix.shape == (3, 3):
cmatrix = matrix[None, :, :]
is_single = True
else:
cmatrix = matrix
cdef Py_ssize_t num_rotations = cmatrix.shape[0]
cdef Py_ssize_t i, j, k
cdef double[:] decision = _empty1(4)
cdef int choice
cdef double[:, :] quat = _empty2(num_rotations, 4)
for ind in range(num_rotations):
decision[0] = cmatrix[ind, 0, 0]
decision[1] = cmatrix[ind, 1, 1]
decision[2] = cmatrix[ind, 2, 2]
decision[3] = cmatrix[ind, 0, 0] + cmatrix[ind, 1, 1] \
+ cmatrix[ind, 2, 2]
choice = _argmax4(decision)
if choice != 3:
i = choice
j = (i + 1) % 3
k = (j + 1) % 3
quat[ind, i] = 1 - decision[3] + 2 * cmatrix[ind, i, i]
quat[ind, j] = cmatrix[ind, j, i] + cmatrix[ind, i, j]
quat[ind, k] = cmatrix[ind, k, i] + cmatrix[ind, i, k]
quat[ind, 3] = cmatrix[ind, k, j] - cmatrix[ind, j, k]
else:
quat[ind, 0] = cmatrix[ind, 2, 1] - cmatrix[ind, 1, 2]
quat[ind, 1] = cmatrix[ind, 0, 2] - cmatrix[ind, 2, 0]
quat[ind, 2] = cmatrix[ind, 1, 0] - cmatrix[ind, 0, 1]
quat[ind, 3] = 1 + decision[3]
# normalize
_normalize4(quat[ind])
if is_single:
return cls(quat[0], normalize=False, copy=False)
else:
return cls(quat, normalize=False, copy=False)
@classmethod
@cython.boundscheck(False)
@cython.wraparound(False)
def from_rotvec(cls, rotvec):
"""Initialize from rotation vectors.
A rotation vector is a 3 dimensional vector which is co-directional to
the axis of rotation and whose norm gives the angle of rotation (in
radians) [1]_.
Parameters
----------
rotvec : array_like, shape (N, 3) or (3,)
A single vector or a stack of vectors, where `rot_vec[i]` gives
the ith rotation vector.
Returns
-------
rotation : `Rotation` instance
Object containing the rotations represented by input rotation
vectors.
References
----------
.. [1] https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation#Rotation_vector
Examples
--------
>>> from scipy.spatial.transform import Rotation as R
Initialize a single rotation:
>>> r = R.from_rotvec(np.pi/2 * np.array([0, 0, 1]))
>>> r.as_rotvec()
array([0. , 0. , 1.57079633])
>>> r.as_rotvec().shape
(3,)
Initialize multiple rotations in one object:
>>> r = R.from_rotvec([
... [0, 0, np.pi/2],
... [np.pi/2, 0, 0]])
>>> r.as_rotvec()
array([[0. , 0. , 1.57079633],
[1.57079633, 0. , 0. ]])
>>> r.as_rotvec().shape
(2, 3)
It is also possible to have a stack of a single rotaton:
>>> r = R.from_rotvec([[0, 0, np.pi/2]])
>>> r.as_rotvec().shape
(1, 3)
"""
is_single = False
rotvec = np.asarray(rotvec, dtype=float)
if rotvec.ndim not in [1, 2] or rotvec.shape[len(rotvec.shape)-1] != 3:
raise ValueError("Expected `rot_vec` to have shape (3,) "
"or (N, 3), got {}".format(rotvec.shape))
# If a single vector is given, convert it to a 2D 1 x 3 matrix but
# set self._single to True so that we can return appropriate objects
# in the `as_...` methods
cdef double[:, :] crotvec
if rotvec.shape == (3,):
crotvec = rotvec[None, :]
is_single = True
else:
crotvec = rotvec
cdef Py_ssize_t num_rotations = crotvec.shape[0]
cdef double angle, scale, angle2
cdef double[:, :] quat = _empty2(num_rotations, 4)
for ind in range(num_rotations):
angle = _norm3(crotvec[ind, :])
if angle <= 1e-3: # small angle
angle2 = angle * angle
scale = 0.5 - angle2 / 48 + angle2 * angle2 / 3840
else: # large angle
scale = sin(angle / 2) / angle
quat[ind, 0] = scale * crotvec[ind, 0]
quat[ind, 1] = scale * crotvec[ind, 1]
quat[ind, 2] = scale * crotvec[ind, 2]
quat[ind, 3] = cos(angle / 2)
if is_single:
return cls(quat[0], normalize=False, copy=False)
else:
return cls(quat, normalize=False, copy=False)
@classmethod
def from_euler(cls, seq, angles, degrees=False):
"""Initialize from Euler angles.
Rotations in 3-D can be represented by a sequence of 3
rotations around a sequence of axes. In theory, any three axes spanning
the 3-D Euclidean space are enough. In practice, the axes of rotation are
chosen to be the basis vectors.
The three rotations can either be in a global frame of reference
(extrinsic) or in a body centred frame of reference (intrinsic), which
is attached to, and moves with, the object under rotation [1]_.
Parameters
----------
seq : string
Specifies sequence of axes for rotations. Up to 3 characters
belonging to the set {'X', 'Y', 'Z'} for intrinsic rotations, or
{'x', 'y', 'z'} for extrinsic rotations. Extrinsic and intrinsic
rotations cannot be mixed in one function call.
angles : float or array_like, shape (N,) or (N, [1 or 2 or 3])
Euler angles specified in radians (`degrees` is False) or degrees
(`degrees` is True).
For a single character `seq`, `angles` can be:
- a single value
- array_like with shape (N,), where each `angle[i]`
corresponds to a single rotation
- array_like with shape (N, 1), where each `angle[i, 0]`
corresponds to a single rotation
For 2- and 3-character wide `seq`, `angles` can be:
- array_like with shape (W,) where `W` is the width of
`seq`, which corresponds to a single rotation with `W` axes
- array_like with shape (N, W) where each `angle[i]`
corresponds to a sequence of Euler angles describing a single
rotation
degrees : bool, optional
If True, then the given angles are assumed to be in degrees.
Default is False.
Returns
-------
rotation : `Rotation` instance
Object containing the rotation represented by the sequence of
rotations around given axes with given angles.
References
----------
.. [1] https://en.wikipedia.org/wiki/Euler_angles#Definition_by_intrinsic_rotations
Examples
--------
>>> from scipy.spatial.transform import Rotation as R
Initialize a single rotation along a single axis:
>>> r = R.from_euler('x', 90, degrees=True)
>>> r.as_quat().shape
(4,)
Initialize a single rotation with a given axis sequence:
>>> r = R.from_euler('zyx', [90, 45, 30], degrees=True)
>>> r.as_quat().shape
(4,)
Initialize a stack with a single rotation around a single axis:
>>> r = R.from_euler('x', [90], degrees=True)
>>> r.as_quat().shape
(1, 4)
Initialize a stack with a single rotation with an axis sequence:
>>> r = R.from_euler('zyx', [[90, 45, 30]], degrees=True)
>>> r.as_quat().shape
(1, 4)
Initialize multiple elementary rotations in one object:
>>> r = R.from_euler('x', [90, 45, 30], degrees=True)
>>> r.as_quat().shape
(3, 4)
Initialize multiple rotations in one object:
>>> r = R.from_euler('zyx', [[90, 45, 30], [35, 45, 90]], degrees=True)
>>> r.as_quat().shape
(2, 4)
"""
num_axes = len(seq)
if num_axes < 1 or num_axes > 3:
raise ValueError("Expected axis specification to be a non-empty "
"string of upto 3 characters, got {}".format(seq))
intrinsic = (re.match(r'^[XYZ]{1,3}$', seq) is not None)
extrinsic = (re.match(r'^[xyz]{1,3}$', seq) is not None)
if not (intrinsic or extrinsic):
raise ValueError("Expected axes from `seq` to be from ['x', 'y', "
"'z'] or ['X', 'Y', 'Z'], got {}".format(seq))
if any(seq[i] == seq[i+1] for i in range(num_axes - 1)):
raise ValueError("Expected consecutive axes to be different, "
"got {}".format(seq))
seq = seq.lower()
angles = np.asarray(angles, dtype=float)
if degrees:
angles = np.deg2rad(angles)
is_single = False
# Prepare angles to have shape (num_rot, num_axes)
if num_axes == 1:
if angles.ndim == 0:
# (1, 1)
angles = angles.reshape((1, 1))
is_single = True
elif angles.ndim == 1:
# (N, 1)
angles = angles[:, None]
elif angles.ndim == 2 and angles.shape[-1] != 1:
raise ValueError("Expected `angles` parameter to have shape "
"(N, 1), got {}.".format(angles.shape))