forked from scipy/scipy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_rotation.pyx
3741 lines (3042 loc) · 132 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
# cython: cpow=True
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, hypot, isnan, NAN, pi
np.import_array()
# utilities for empty array initialization
cdef inline double[:] _empty1(int n) noexcept:
return array(shape=(n,), itemsize=sizeof(double), format=b"d")
cdef inline double[:, :] _empty2(int n1, int n2) noexcept :
return array(shape=(n1, n2), itemsize=sizeof(double), format=b"d")
cdef inline double[:, :, :] _empty3(int n1, int n2, int n3) noexcept:
return array(shape=(n1, n2, n3), itemsize=sizeof(double), format=b"d")
cdef inline double[:, :] _zeros2(int n1, int n2) noexcept:
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) noexcept:
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) noexcept 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) noexcept nogil:
return sqrt(_dot3(elems, elems))
@cython.boundscheck(False)
@cython.wraparound(False)
cdef inline double _normalize4(double[:] elems) noexcept 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) noexcept 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) noexcept:
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 inline int _elementary_basis_index(uchar axis) noexcept:
if axis == b'x': return 0
elif axis == b'y': return 1
elif axis == b'z': return 2
# Reduce the quaternion double coverage of the rotation group to a unique
# canonical "positive" single cover
@cython.boundscheck(False)
@cython.wraparound(False)
cdef inline void _quat_canonical_single(double[:] q) noexcept nogil:
if ((q[3] < 0)
or (q[3] == 0 and q[0] < 0)
or (q[3] == 0 and q[0] == 0 and q[1] < 0)
or (q[3] == 0 and q[0] == 0 and q[1] == 0 and q[2] < 0)):
q[0] *= -1.0
q[1] *= -1.0
q[2] *= -1.0
q[3] *= -1.0
@cython.boundscheck(False)
@cython.wraparound(False)
cdef inline void _quat_canonical(double[:, :] q) noexcept:
cdef Py_ssize_t n = q.shape[0]
for ind in range(n):
_quat_canonical_single(q[ind])
@cython.boundscheck(False)
@cython.wraparound(False)
cdef inline void _get_angles(
double[:] angles, bint extrinsic, bint symmetric, bint sign,
double lamb, double a, double b, double c, double d):
# intrinsic/extrinsic conversion helpers
cdef int angle_first, angle_third
if extrinsic:
angle_first = 0
angle_third = 2
else:
angle_first = 2
angle_third = 0
cdef double half_sum, half_diff
cdef int case
# Step 2
# Compute second angle...
angles[1] = 2 * atan2(hypot(c, d), hypot(a, b))
# ... and check if equal to is 0 or pi, causing a singularity
if abs(angles[1]) <= 1e-7:
case = 1
elif abs(angles[1] - <double>pi) <= 1e-7:
case = 2
else:
case = 0 # normal case
# Step 3
# compute first and third angles, according to case
half_sum = atan2(b, a)
half_diff = atan2(d, c)
if case == 0: # no singularities
angles[angle_first] = half_sum - half_diff
angles[angle_third] = half_sum + half_diff
else: # any degenerate case
angles[2] = 0
if case == 1:
angles[0] = 2 * half_sum
else:
angles[0] = 2 * half_diff * (-1 if extrinsic else 1)
# for Tait-Bryan/asymmetric sequences
if not symmetric:
angles[angle_third] *= sign
angles[1] -= lamb
for idx in range(3):
if angles[idx] < -pi:
angles[idx] += 2 * pi
elif angles[idx] > pi:
angles[idx] -= 2 * pi
if case != 0:
warnings.warn("Gimbal lock detected. Setting third angle to zero "
"since it is not possible to uniquely determine "
"all angles.", stacklevel=3)
@cython.boundscheck(False)
@cython.wraparound(False)
cdef double[:, :] _compute_euler_from_matrix(
np.ndarray[double, ndim=3] matrix, const uchar[:] seq, bint extrinsic
) noexcept:
# This is being replaced by the newer: _compute_euler_from_quat
#
# 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
#
# Based on Malcolm D. Shuster, F. Landis Markley, "General formula for
# extraction the Euler angles", Journal of guidance, control, and
# dynamics, vol. 29.1, pp. 215-221. 2006
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 intrinsic, 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
if extrinsic:
# reversal
_angles[0], _angles[2] = _angles[2], _angles[0]
# 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.")
return angles
@cython.boundscheck(False)
@cython.wraparound(False)
cdef double[:, :] _compute_euler_from_quat(
np.ndarray[double, ndim=2] quat, const uchar[:] seq, bint extrinsic
) noexcept:
# The algorithm assumes extrinsic frame transformations. The algorithm
# in the paper is formulated for rotation quaternions, which are stored
# directly by Rotation.
# Adapt the algorithm for our case by reversing both axis sequence and
# angles for intrinsic rotations when needed
if not extrinsic:
seq = seq[::-1]
cdef int i = _elementary_basis_index(seq[0])
cdef int j = _elementary_basis_index(seq[1])
cdef int k = _elementary_basis_index(seq[2])
cdef bint symmetric = i == k
if symmetric:
k = 3 - i - j # get third axis
# Step 0
# Check if permutation is even (+1) or odd (-1)
cdef int sign = (i - j) * (j - k) * (k - i) // 2
cdef Py_ssize_t num_rotations = quat.shape[0]
# some forward definitions
cdef double a, b, c, d
cdef double[:, :] angles = _empty2(num_rotations, 3)
for ind in range(num_rotations):
# Step 1
# Permutate quaternion elements
if symmetric:
a = quat[ind, 3]
b = quat[ind, i]
c = quat[ind, j]
d = quat[ind, k] * sign
else:
a = quat[ind, 3] - quat[ind, j]
b = quat[ind, i] + quat[ind, k] * sign
c = quat[ind, j] + quat[ind, 3]
d = quat[ind, k] * sign - quat[ind, i]
_get_angles(angles[ind], extrinsic, symmetric, sign, pi / 2, a, b, c, d)
return angles
@cython.boundscheck(False)
@cython.wraparound(False)
cdef double[:, :] _compute_davenport_from_quat(
np.ndarray[double, ndim=2] quat, np.ndarray[double, ndim=1] n1,
np.ndarray[double, ndim=1] n2, np.ndarray[double, ndim=1] n3,
bint extrinsic
):
# The algorithm assumes extrinsic frame transformations. The algorithm
# in the paper is formulated for rotation quaternions, which are stored
# directly by Rotation.
# Adapt the algorithm for our case by reversing both axis sequence and
# angles for intrinsic rotations when needed
if not extrinsic:
n1, n3 = n3, n1
cdef double[:] n_cross = _cross3(n1, n2)
cdef double lamb = atan2(_dot3(n3, n_cross), _dot3(n3, n1))
cdef int correct_set = False
if lamb < 0:
# alternative set of angles compatible with as_euler implementation
n2 = -n2
lamb = -lamb
n_cross[0] = -n_cross[0]
n_cross[1] = -n_cross[1]
n_cross[2] = -n_cross[2]
correct_set = True
cdef double[:] quat_lamb = np.array([
sin(lamb / 2) * n2[0],
sin(lamb / 2) * n2[1],
sin(lamb / 2) * n2[2],
cos(lamb / 2)]
)
cdef Py_ssize_t num_rotations = quat.shape[0]
# some forward definitions
cdef double[:, :] angles = _empty2(num_rotations, 3)
cdef double[:] quat_transformed = _empty1(4)
cdef double a, b, c, d
for ind in range(num_rotations):
_compose_quat_single(quat_lamb, quat[ind], quat_transformed)
# Step 1
# Permutate quaternion elements
a = quat_transformed[3]
b = _dot3(quat_transformed[:3], n1)
c = _dot3(quat_transformed[:3], n2)
d = _dot3(quat_transformed[:3], n_cross)
_get_angles(angles[ind], extrinsic, False, 1, lamb, a, b, c, d)
if correct_set:
angles[ind, 1] = -angles[ind, 1]
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
) noexcept:
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
) noexcept:
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
) noexcept:
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
) noexcept:
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
def _format_angles(angles, degrees, num_axes):
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))
elif angles.ndim > 2:
raise ValueError("Expected float, 1D array, or 2D array for "
"parameter `angles` corresponding to `seq`, "
"got shape {}.".format(angles.shape))
else: # 2 or 3 axes
if angles.ndim not in [1, 2] or angles.shape[-1] != num_axes:
raise ValueError("Expected `angles` to be at most "
"2-dimensional with width equal to number "
"of axes specified, got "
"{} for shape".format(angles.shape))
if angles.ndim == 1:
# (1, num_axes)
angles = angles[None, :]
is_single = True
# By now angles should have shape (num_rot, num_axes)
# sanity check
if angles.ndim != 2 or angles.shape[-1] != num_axes:
raise ValueError("Expected angles to have shape (num_rotations, "
"num_axes), got {}.".format(angles.shape))
return angles, is_single
cdef class Rotation:
"""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
from_davenport
as_quat
as_matrix
as_rotvec
as_mrp
as_euler
as_davenport
concatenate
apply
__mul__
__pow__
inv
magnitude
approx_equal
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
>>> import numpy as np
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])
A rotation can be composed with itself using the ``**`` operator:
>>> p = R.from_rotvec([1, 0, 0])
>>> q = p ** 2
>>> q.as_rotvec()
array([2., 0., 0.])
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.]])
The following function can be used to plot rotations with Matplotlib by
showing how they transform the standard x, y, z coordinate axes:
>>> import matplotlib.pyplot as plt
>>> def plot_rotated_axes(ax, r, name=None, offset=(0, 0, 0), scale=1):
... colors = ("#FF6666", "#005533", "#1199EE") # Colorblind-safe RGB
... loc = np.array([offset, offset])
... for i, (axis, c) in enumerate(zip((ax.xaxis, ax.yaxis, ax.zaxis),
... colors)):
... axlabel = axis.axis_name
... axis.set_label_text(axlabel)
... axis.label.set_color(c)
... axis.line.set_color(c)
... axis.set_tick_params(colors=c)
... line = np.zeros((2, 3))
... line[1, i] = scale
... line_rot = r.apply(line)
... line_plot = line_rot + loc
... ax.plot(line_plot[:, 0], line_plot[:, 1], line_plot[:, 2], c)
... text_loc = line[1]*1.2
... text_loc_rot = r.apply(text_loc)
... text_plot = text_loc_rot + loc[0]
... ax.text(*text_plot, axlabel.upper(), color=c,
... va="center", ha="center")
... ax.text(*offset, name, color="k", va="center", ha="center",
... bbox={"fc": "w", "alpha": 0.8, "boxstyle": "circle"})
Create three rotations - the identity and two Euler rotations using
intrinsic and extrinsic conventions:
>>> r0 = R.identity()
>>> r1 = R.from_euler("ZYX", [90, -30, 0], degrees=True) # intrinsic
>>> r2 = R.from_euler("zyx", [90, -30, 0], degrees=True) # extrinsic
Add all three rotations to a single plot:
>>> ax = plt.figure().add_subplot(projection="3d", proj_type="ortho")
>>> plot_rotated_axes(ax, r0, name="r0", offset=(0, 0, 0))
>>> plot_rotated_axes(ax, r1, name="r1", offset=(3, 0, 0))
>>> plot_rotated_axes(ax, r2, name="r2", offset=(6, 0, 0))
>>> _ = ax.annotate(
... "r0: Identity Rotation\\n"
... "r1: Intrinsic Euler Rotation (ZYX)\\n"
... "r2: Extrinsic Euler Rotation (zyx)",
... xy=(0.6, 0.7), xycoords="axes fraction", ha="left"
... )
>>> ax.set(xlim=(-1.25, 7.25), ylim=(-1.25, 1.25), zlim=(-1.25, 1.25))
>>> ax.set(xticks=range(-1, 8), yticks=[-1, 0, 1], zticks=[-1, 0, 1])
>>> ax.set_aspect("equal", adjustable="box")
>>> ax.figure.set_size_inches(6, 5)
>>> plt.tight_layout()
Show the plot:
>>> plt.show()
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, scalar_first=False):
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, 4), "
f"got {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 scalar_first:
quat = np.roll(quat, -1, axis=1)
elif normalize or copy:
quat = quat.copy()
if normalize:
for ind in range(num_rotations):
if isnan(_normalize4(quat[ind, :])):
raise ValueError("Found zero norm quaternions in `quat`.")
self._quat = 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 __bool__(self):
"""Comply with Python convention for objects to be True.
Required because `Rotation.__len__()` is defined and not always truthy.
"""
return True
@cython.embedsignature(True)
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]
@cython.embedsignature(True)
@classmethod
def from_quat(cls, quat, *, scalar_first=False):
"""Initialize from quaternions.
Rotations in 3 dimensions can be represented using unit norm
quaternions [1]_.
The 4 components of a quaternion are divided into a scalar part ``w``
and a vector part ``(x, y, z)`` and can be expressed from the angle
``theta`` and the axis ``n`` of a rotation as follows::
w = cos(theta / 2)
x = sin(theta / 2) * n_x
y = sin(theta / 2) * n_y
z = sin(theta / 2) * n_z
There are 2 conventions to order the components in a quaternion:
- scalar-first order -- ``(w, x, y, z)``
- scalar-last order -- ``(x, y, z, w)``
The choice is controlled by `scalar_first` argument.
By default, it is False and the scalar-last order is assumed.
Advanced users may be interested in the "double cover" of 3D space by
the quaternion representation [2]_. As of version 1.11.0, the
following subset (and only this subset) of operations on a `Rotation`
``r`` corresponding to a quaternion ``q`` are guaranteed to preserve
the double cover property: ``r = Rotation.from_quat(q)``,
``r.as_quat(canonical=False)``, ``r.inv()``, and composition using the
``*`` operator such as ``r*r``.
Parameters
----------
quat : array_like, shape (N, 4) or (4,)
Each row is a (possibly non-unit norm) quaternion representing an
active rotation. Each quaternion will be normalized to unit norm.
scalar_first : bool, optional
Whether the scalar component goes first or last.
Default is False, i.e. the scalar-last order is assumed.
Returns
-------
rotation : `Rotation` instance
Object containing the rotations represented by input quaternions.
References
----------
.. [1] https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation
.. [2] Hanson, Andrew J. "Visualizing quaternions."
Morgan Kaufmann Publishers Inc., San Francisco, CA. 2006.
Examples
--------
>>> from scipy.spatial.transform import Rotation as R
A rotation can be initialzied from a quaternion with the scalar-last
(default) or scalar-first component order as shown below:
>>> r = R.from_quat([0, 0, 0, 1])
>>> r.as_matrix()
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
>>> r = R.from_quat([1, 0, 0, 0], scalar_first=True)
>>> r.as_matrix()
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
It is possible to initialize multiple rotations in a single object by
passing a 2-dimensional array:
>>> 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, scalar_first=scalar_first)
@cython.embedsignature(True)
@classmethod