-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathRotation.py
1999 lines (1706 loc) · 80.2 KB
/
Rotation.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
"""A pytorch implementation of scipy.spatial.transform.Rotation.
A container for proper and improper Rotations, that can be created from quaternions, euler angles, rotation vectors,
rotation matrices, etc, can be applied to torch.Tensors and SpatialDimensions, multiplied, and can be converted
to quaternions, euler angles, etc.
see also https://github.com/scipy/scipy/blob/main/scipy/spatial/transform/_rotation.pyx
"""
# based on Scipy implementation, which has the following copyright:
# Copyright (c) 2001-2002 Enthought, Inc. 2003-2024, SciPy Developers
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import annotations
import math
import re
import warnings
from collections.abc import Callable, Sequence
from typing import Literal, cast
import numpy as np
import torch
import torch.nn.functional as F # noqa: N812
from einops import rearrange
from scipy._lib._util import check_random_state
from typing_extensions import Self, Unpack, overload
from mrpro.data.SpatialDimension import SpatialDimension
from mrpro.utils.typing import NestedSequence, TorchIndexerType
from mrpro.utils.vmf import sample_vmf
AXIS_ORDER = 'zyx' # This can be modified
QUAT_AXIS_ORDER = AXIS_ORDER + 'w' # Do not modify
assert QUAT_AXIS_ORDER[:3] == AXIS_ORDER, 'Quaternion axis order has to match axis order' # noqa: S101
def _compose_quaternions_single(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
"""Calculate p * q."""
cross = torch.linalg.cross(p[:3], q[:3])
product = torch.stack(
(
p[3] * q[0] + q[3] * p[0] + cross[0],
p[3] * q[1] + q[3] * p[1] + cross[1],
p[3] * q[2] + q[3] * p[2] + cross[2],
p[3] * q[3] - p[0] * q[0] - p[1] * q[1] - p[2] * q[2],
),
0,
)
return product
def _compose_quaternions(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
"""Calculate p * q, with p and q batched quaternions."""
p, q = torch.broadcast_tensors(p, q)
product = torch.vmap(_compose_quaternions_single)(p.reshape(-1, 4), q.reshape(-1, 4)).reshape(p.shape)
return product
def _canonical_quaternion(quaternion: torch.Tensor) -> torch.Tensor:
"""Convert to canonical form, i.e. positive w."""
x, y, z, w = (quaternion[..., QUAT_AXIS_ORDER.index(axis)] for axis in 'xyzw')
needs_inversion = (w < 0) | ((w == 0) & ((x < 0) | ((x == 0) & ((y < 0) | ((y == 0) & (z < 0))))))
canonical_quaternion = torch.where(needs_inversion.unsqueeze(-1), -quaternion, quaternion)
return canonical_quaternion
def _matrix_to_quaternion(matrix: torch.Tensor) -> torch.Tensor:
"""Convert matrix to quaternion."""
if matrix.shape[-2:] != (3, 3):
raise ValueError(f'Invalid rotation matrix shape {matrix.shape}.')
batch_shape = matrix.shape[:-2]
# matrix elements
m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.unbind(matrix.flatten(start_dim=-2), -1)
# q,r,s are some permutation of x,y,z
qrsw = torch.nn.functional.relu(
torch.stack(
[
1.0 + m00 - m11 - m22,
1.0 - m00 + m11 - m22,
1.0 - m00 - m11 + m22,
1.0 + m00 + m11 + m22,
],
dim=-1,
)
)
q, r, s, w = qrsw.unbind(-1)
# all these are the same except in edge cases.
# we will choose the one that is most numerically stable.
# we calculate all choices as this is faster
candidates = torch.stack(
(
*(q, m10 + m01, m02 + m20, m21 - m12),
*(m10 + m01, r, m12 + m21, m02 - m20),
*(m20 + m02, m21 + m12, s, m10 - m01),
*(m21 - m12, m02 - m20, m10 - m01, w),
),
dim=-1,
).reshape(*batch_shape, 4, 4)
# now we make the choice.
# the choice will not influence the gradients.
choice = qrsw.argmax(dim=-1)
quaternion = candidates.take_along_dim(choice[..., None, None], -2).squeeze(-2) / (
qrsw.take_along_dim(choice[..., None], -1).sqrt() * 2
)
return quaternion
def _make_elementary_quat(axis: str, angle: torch.Tensor):
"""Make a quaternion for the rotation around one of the axes."""
quat = torch.zeros(*angle.shape, 4, device=angle.device, dtype=angle.dtype)
axis_index = QUAT_AXIS_ORDER.index(axis)
w_index = QUAT_AXIS_ORDER.index('w')
quat[..., w_index] = torch.cos(angle / 2)
quat[..., axis_index] = torch.sin(angle / 2)
return quat
def _quaternion_to_matrix(quaternion: torch.Tensor) -> torch.Tensor:
"""Convert quaternion to rotation matrix."""
# use same order for quaternions as for matrix. this saves two index lookups.
# we use q, r, s for a permutation of x, y, z
# as this function will be used for the application of the rotatoin matrix, it should be fast.
q, r, s, w = quaternion.unbind(-1)
qq = q.square()
rr = r.square()
ss = s.square()
ww = w.square()
qr = q * r
sw = s * w
qs = q * s
rw = r * w
rs = r * s
qw = q * w
matrix = torch.stack(
(
*(qq - rr - ss + ww, 2 * (qr - sw), 2 * (qs + rw)),
*(2 * (qr + sw), -qq + rr - ss + ww, 2 * (rs - qw)),
*(2 * (qs - rw), 2 * (rs + qw), -qq - rr + ss + ww),
),
dim=-1,
).reshape(*quaternion.shape[:-1], 3, 3)
return matrix
def _quaternion_to_axis_angle(quaternion: torch.Tensor, degrees: bool = False) -> tuple[torch.Tensor, torch.Tensor]:
"""Convert quaternion to rotation axis and angle.
Parameters
----------
quaternion
The batched quaternions, shape (..., 4)
degrees
If True, the angle is returned in degrees, otherwise in radians.
Returns
-------
axis
The rotation axis, shape (..., 3)
angle
The rotation angle, shape (...)
"""
quaternion = _canonical_quaternion(quaternion)
angle = 2 * torch.atan2(torch.linalg.vector_norm(quaternion[..., :3], dim=-1), quaternion[..., 3])
axis = quaternion[..., :3] / torch.linalg.vector_norm(quaternion[..., :3], dim=-1, keepdim=True)
if degrees:
angle = torch.rad2deg(angle)
return axis, angle
def _quaternion_to_euler(quaternion: torch.Tensor, seq: str, extrinsic: bool):
"""Convert quaternion to euler angles.
Parameters
----------
quaternion
The batched quaternions
seq
The axes sequence, lower case. For example 'xyz'
extrinsic
If the rotations are extrinsic (True) or intrinsic (False)
"""
# 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]
q, r, s = (QUAT_AXIS_ORDER.index(axis) for axis in seq) # one of x,y,z
w = QUAT_AXIS_ORDER.index('w')
# proper angles, with first and last axis the same
if symmetric := q == s:
s = 3 - q - r # get third axis
# Check if permutation is even (+1) or odd (-1)
sign = (q - r) * (r - s) * (s - q) // 2
if symmetric:
a = quaternion[..., w]
b = quaternion[..., q]
c = quaternion[..., r]
d = quaternion[..., s] * sign
else:
a = quaternion[..., w] - quaternion[..., r]
b = quaternion[..., q] + quaternion[..., s] * sign
c = quaternion[..., r] + quaternion[..., w]
d = quaternion[..., s] * sign - quaternion[..., q]
# Compute angles
angles_1 = 2 * torch.atan2(torch.hypot(c, d), torch.hypot(a, b))
half_sum = torch.atan2(b, a)
half_diff = torch.atan2(d, c)
angles_0 = half_sum - half_diff
angles_2 = half_sum + half_diff
if not symmetric:
angles_2 *= sign
angles_1 -= torch.pi / 2
if not extrinsic:
# flip first and last rotation
angles_2, angles_0 = angles_0, angles_2
# Check if angles_1 is equal to is 0 (case=1) or pi (case=2), causing a singularity,
# i.e. a gimble lock. case=0 is the normal.
case = 1 * (torch.abs(angles_1) <= 1e-7) + 2 * (torch.abs(angles_1 - torch.pi) <= 1e-7)
# if Gimbal lock, sett last angle to 0 and use 2 * half_sum / 2 * half_diff for first angle.
angles_2 = (case == 0) * angles_2
angles_0 = (
(case == 0) * angles_0 + (case == 1) * 2 * half_sum + (case == 2) * 2 * half_diff * (-1 if extrinsic else 1)
)
angles = torch.stack((angles_0, angles_1, angles_2), -1)
angles += (angles < -torch.pi) * 2 * torch.pi
angles -= (angles > torch.pi) * 2 * torch.pi
return angles
def _align_vectors(
a: torch.Tensor,
b: torch.Tensor,
weights: torch.Tensor,
return_sensitivity: bool = False,
allow_improper: bool = False,
):
"""Estimate a rotation to optimally align two sets of vectors."""
n_vecs = a.shape[0]
if a.shape != b.shape:
raise ValueError(f'Expected inputs to have same shapes, got {a.shape} and {b.shape}')
if a.shape[-1] != 3:
raise ValueError(f'Expected inputs to have shape (..., 3), got {a.shape} and {b.shape}')
if weights.shape != (n_vecs,) or (weights < 0).any():
raise ValueError(f'Invalid weights: expected shape ({n_vecs},) with non-negative values')
if (a.norm(dim=-1) < 1e-6).any() or (b.norm(dim=-1) < 1e-6).any():
raise ValueError('Cannot align zero length primary vectors')
dtype = torch.result_type(a, b)
# we require double precision for the calculations to match scipy results
weights = weights.double()
a = a.double()
b = b.double()
inf_mask = torch.isinf(weights)
if inf_mask.sum() > 1:
raise ValueError('Only one infinite weight is allowed')
if inf_mask.any() or n_vecs == 1:
# special case for one vector pair or one infinite weight
if return_sensitivity:
raise ValueError('Cannot return sensitivity matrix with an infinite weight or one vector pair')
a_primary, b_primary = (a[0], b[0]) if n_vecs == 1 else (a[inf_mask][0], b[inf_mask][0])
a_primary, b_primary = F.normalize(a_primary, dim=0), F.normalize(b_primary, dim=0)
cross = torch.linalg.cross(b_primary, a_primary, dim=0)
angle = torch.atan2(torch.norm(cross), torch.dot(a_primary, b_primary))
rot_primary = _axisangle_to_matrix(cross, angle)
if n_vecs == 1:
return rot_primary.to(dtype), torch.tensor(0.0, device=a.device, dtype=dtype)
a_secondary, b_secondary = a[~inf_mask], b[~inf_mask]
sec_w = weights[~inf_mask]
rot_sec_b = (rot_primary @ b_secondary.T).T
sin_term = torch.einsum('ij,j->i', torch.linalg.cross(rot_sec_b, a_secondary, dim=1), a_primary)
cos_term = torch.einsum('ij,ij->i', rot_sec_b, a_secondary) - torch.einsum(
'ij,j->i', rot_sec_b, a_primary
) * torch.einsum('ij,j->i', a_secondary, a_primary)
phi = torch.atan2((sec_w * sin_term).sum(), (sec_w * cos_term).sum())
rot_secondary = _axisangle_to_matrix(a_primary, phi)
rot_optimal = rot_secondary @ rot_primary
rssd_w = weights.clone()
rssd_w[inf_mask] = 0
est_a = (rot_optimal @ b.T).T
rssd = torch.sqrt(torch.sum(rssd_w * torch.sum((a - est_a) ** 2, dim=1)))
return rot_optimal.to(dtype), rssd.to(dtype)
corr_mat = torch.einsum('i j, i k, i -> j k', a, b, weights)
u, s, vt = cast(tuple[torch.Tensor, torch.Tensor, torch.Tensor], torch.linalg.svd(corr_mat))
if s[1] + s[2] < 1e-16 * s[0]:
warnings.warn('Optimal rotation is not uniquely or poorly defined for the given sets of vectors.', stacklevel=2)
if (u @ vt).det() < 0 and not allow_improper:
u[:, -1] *= -1
rot_optimal = (u @ vt).to(dtype)
rssd = ((weights * (b**2 + a**2).sum(dim=1)).sum() - 2 * s.sum()).clamp_min(0.0).sqrt().to(dtype)
if return_sensitivity:
zeta = (s[0] + s[1]) * (s[1] + s[2]) * (s[2] + s[0])
kappa = s[0] * s[1] + s[1] * s[2] + s[2] * s[0]
sensitivity = (
weights.mean() / zeta * (kappa * torch.eye(3, device=a.device, dtype=torch.float64) + corr_mat @ corr_mat.T)
).to(dtype)
return rot_optimal, rssd, sensitivity
return rot_optimal, rssd
def _axisangle_to_matrix(axis: torch.Tensor, angle: torch.Tensor) -> torch.Tensor:
"""Compute a rotation matrix using Rodrigues' rotation formula."""
axis = F.normalize(axis, dim=-1, eps=1e-6)
cos, sin = torch.cos(angle), torch.sin(angle)
t = 1 - cos
q, r, s = axis.unbind(-1)
matrix = rearrange(
torch.stack(
[
t * q * q + cos,
t * q * r - s * sin,
t * q * s + r * sin,
t * q * r + s * sin,
t * r * r + cos,
t * r * s - q * sin,
t * q * s - r * sin,
t * r * s + q * sin,
t * s * s + cos,
],
dim=-1,
),
'... (row col) -> ... row col',
row=3,
)
return matrix
class Rotation(torch.nn.Module):
"""A container for Rotations.
A pytorch implementation of scipy.spatial.transform.Rotation.
For more information see the scipy documentation:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.transform.Rotation.html
Differences compared to scipy.spatial.transform.Rotation:
- torch.nn.Module based, the quaternions are a Parameter
- not all features are implemented. Notably, mrp, davenport, and reduce are missing.
- arbitrary number of batching dimensions
- support for improper rotations (rotoinversion), i.e., rotations with an coordinate inversion
or a reflection about a plane perpendicular to the rotation axis.
"""
def __init__(
self,
quaternions: torch.Tensor | NestedSequence[float],
normalize: bool = True,
copy: bool = True,
inversion: torch.Tensor | NestedSequence[bool] | bool = False,
reflection: torch.Tensor | NestedSequence[bool] | bool = False,
) -> None:
"""Initialize a new Rotation.
Instead of calling this method, also consider the different ``from_*`` class methods to construct a Rotation.
Parameters
----------
quaternions
Rotatation quaternions. If these requires_grad, the resulting Rotation will require gradients
normalize
If the quaternions should be normalized. Only disable if you are sure the quaternions are already
normalized.
Will keep a possible negative w to represent improper rotations.
copy
Always ensure that a copy of the quaternions is created. If both normalize and copy are False,
the quaternions Parameter of this instance will be a view if the quaternions passed in.
inversion
If the rotation should contain an inversion of the coordinate system, i.e. a reflection of all three axes,
resulting in a rotoinversion (improper rotation).
If a boolean tensor is given, it should broadcast with the quaternions.
reflection
If the rotation should contain a reflection about a plane perpendicular to the rotation axis.
This will result in a rotoflexion (improper rotation).
If a boolean tensor is given, it should broadcast with the quaternions.
"""
super().__init__()
quaternions_ = torch.as_tensor(quaternions)
if torch.is_complex(quaternions_):
raise ValueError('quaternions should be real numbers')
if not torch.is_floating_point(quaternions_):
# integer or boolean dtypes
quaternions_ = quaternions_.float()
if quaternions_.shape[-1] != 4:
raise ValueError('Expected `quaternions` to have shape (..., 4), ' f'got {quaternions_.shape}.')
reflection_ = torch.as_tensor(reflection)
inversion_ = torch.as_tensor(inversion)
if reflection_.any():
axis, angle = _quaternion_to_axis_angle(quaternions_)
angle = (angle + torch.pi * reflection_.float()).unsqueeze(-1)
is_improper = inversion_ ^ reflection_
quaternions_ = torch.cat((torch.sin(angle / 2) * axis, torch.cos(angle / 2)), -1)
elif inversion_.any():
is_improper = inversion_
else:
is_improper = torch.zeros_like(quaternions_[..., 0], dtype=torch.bool)
batchsize = torch.broadcast_shapes(quaternions_.shape[:-1], is_improper.shape)
is_improper = is_improper.expand(batchsize)
# 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 quaternions_.shape == (4,):
quaternions_ = quaternions_[None, :]
is_improper = is_improper[None]
self._single = True
else:
self._single = False
if normalize:
norms = torch.linalg.vector_norm(quaternions_, dim=-1, keepdim=True)
if torch.any(torch.isclose(norms.float(), torch.tensor(0.0))):
raise ValueError('Found zero norm quaternion in `quaternions`.')
quaternions_ = quaternions_ / norms
elif copy:
# no need to clone if we are normalizing
quaternions_ = quaternions_.clone()
if copy:
is_improper = is_improper.clone()
if is_improper.requires_grad:
warnings.warn('Rotation is not differentiable in the improper parameter.', stacklevel=2)
self._quaternions = torch.nn.Parameter(quaternions_, quaternions_.requires_grad)
self._is_improper = torch.nn.Parameter(is_improper, False)
@property
def single(self) -> bool:
"""Returns true if this a single rotation."""
return self._single
@property
def is_improper(self) -> torch.Tensor:
"""Returns a true boolean tensor if the rotation is improper."""
return self._is_improper
@is_improper.setter
def is_improper(self, improper: torch.Tensor | NestedSequence[bool] | bool) -> None:
"""Set the improper parameter."""
self._is_improper[:] = torch.as_tensor(improper, dtype=torch.bool, device=self._is_improper.device)
@property
def det(self) -> torch.Tensor:
"""Returns the determinant of the rotation matrix.
Will be 1. for proper rotations and -1. for improper rotations.
"""
return self._is_improper.float() * -2 + 1
@classmethod
def from_quat(
cls,
quaternions: torch.Tensor | NestedSequence[float],
inversion: torch.Tensor | NestedSequence[bool] | bool = False,
reflection: torch.Tensor | NestedSequence[bool] | bool = False,
) -> Self:
"""Initialize from quaternions.
3D rotations can be represented using unit-norm quaternions [QUAa]_.
As an extension to the standard, this class also supports improper rotations,
i.e. rotations with reflection with respect to the plane perpendicular to the rotation axis
or inversion of the coordinate system.
Note: If inversion != reflection, the rotation will be improper and save as a rotation followed by an inversion.
containing an inversion of the coordinate system.
Parameters
----------
quaternions
shape (..., 4)
Each row is a (possibly non-unit norm) quaternion representing an
active rotation, in scalar-last (x, y, z, w) format. Each
quaternion will be normalized to unit norm.
inversion
if the rotation should contain an inversion of the coordinate system, i.e. a reflection
of all three axes. If a boolean tensor is given, it should broadcast with the quaternions.
reflection
if the rotation should contain a reflection about a plane perpendicular to the rotation axis.
Returns
-------
rotation
Object containing the rotations represented by input quaternions.
References
----------
.. [QUAa] Quaternions and spatial rotation https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation
"""
return cls(quaternions, normalize=True, copy=True, inversion=inversion, reflection=reflection)
@classmethod
def from_matrix(cls, matrix: torch.Tensor | NestedSequence[float], allow_improper: bool = True) -> Self:
"""Initialize from rotation matrix.
Rotations in 3 dimensions can be represented with 3 x 3 proper
orthogonal matrices [ROTa]_. If the input is not proper orthogonal,
an approximation is created using the method described in [MAR2008]_.
If the input matrix has a negative determinant, the rotation is considered
as improper, i.e. containing a reflection. The resulting rotation
will include this reflection [ROTb]_.
Parameters
----------
matrix
A single matrix or a stack of matrices, shape (..., 3, 3)
allow_improper
If true, the rotation is considered as improper if the determinant of the matrix is negative.
If false, an ValueError is raised if the determinant is negative.
Returns
-------
rotation
Object containing the rotations represented by the rotation
matrices.
References
----------
.. [ROTa] Rotation matrix https://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions
.. [ROTb] Rotation matrix https://en.wikipedia.org/wiki/Improper_rotation
.. [MAR2008] Landis Markley F (2008) Unit Quaternion from Rotation Matrix, Journal of guidance, control, and
dynamics 31(2),440-442.
"""
matrix_ = torch.as_tensor(matrix)
if matrix_.shape[-2:] != (3, 3):
raise ValueError(f'Expected `matrix` to have shape (..., 3, 3), got {matrix_.shape}')
if torch.is_complex(matrix_):
raise ValueError('matrix should be real, not complex.')
if not torch.is_floating_point(matrix_):
# integer or boolean dtypes
matrix_ = matrix_.float()
det = torch.linalg.det(matrix_)
improper = det < 0
if improper.any():
if not allow_improper:
raise ValueError(
'Found negative determinant in `matrix`. '
'This would result in an improper rotation, but allow_improper is False.'
)
matrix_ = matrix_ * det.unsqueeze(-1).unsqueeze(-1).sign()
quaternions = _matrix_to_quaternion(matrix_)
return cls(quaternions, normalize=True, copy=False, inversion=improper, reflection=False)
@classmethod
def from_directions(
cls, *basis: Unpack[tuple[SpatialDimension, SpatialDimension, SpatialDimension]], allow_improper: bool = True
):
"""Initialize from basis vectors as SpatialDimensions.
Parameters
----------
*basis
3 Basis vectors of the new coordinate system, i.e. the columns of the rotation matrix
allow_improper
If true, the rotation is considered as improper if the determinant of the matrix is negative
and the sign will be preserved. If false, a ValueError is raised if the determinant is negative.
Returns
-------
rotation
Object containing the rotations represented by the basis vectors.
"""
b1, b2, b3 = (torch.stack([torch.as_tensor(getattr(v_, axis)) for axis in AXIS_ORDER], -1) for v_ in basis)
matrix = torch.stack((b1, b2, b3), -1)
det = torch.linalg.det(matrix)
if not allow_improper and (det < 0).any():
raise ValueError('The given basis vectors do not form a proper rotation matrix.')
if ((1 - det.abs()) > 0.1).any():
raise ValueError('The given basis vectors do not form a rotation matrix.')
return cls.from_matrix(matrix, allow_improper=allow_improper)
def as_directions(
self,
) -> tuple[SpatialDimension[torch.Tensor], SpatialDimension[torch.Tensor], SpatialDimension[torch.Tensor]]:
"""Represent as the basis vectors of the new coordinate system as SpatialDimensions.
Returns the three basis vectors of the new coordinate system after rotation,
i.e. the columns of the rotation matrix, as SpatialDimensions.
Returns
-------
basis
The basis vectors of the new coordinate system.
"""
matrix = self.as_matrix()
ret = (
SpatialDimension(**dict(zip(AXIS_ORDER, matrix[..., 0].unbind(-1), strict=True))),
SpatialDimension(**dict(zip(AXIS_ORDER, matrix[..., 1].unbind(-1), strict=True))),
SpatialDimension(**dict(zip(AXIS_ORDER, matrix[..., 2].unbind(-1), strict=True))),
)
return ret
@classmethod
def from_rotvec(
cls,
rotvec: torch.Tensor | NestedSequence[float],
degrees: bool = False,
reflection: torch.Tensor | NestedSequence[bool] | bool = False,
inversion: torch.Tensor | NestedSequence[bool] | bool = False,
) -> Self:
"""Initialize from rotation vector.
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.
Parameters
----------
rotvec
shape (..., 3), the rotation vectors.
degrees
If True, then the given angles are assumed to be in degrees,
otherwise radians.
reflection
If True, the resulting transformation will contain a reflection
about a plane perpendicular to the rotation axis, resulting in a rotoflection
(improper rotation).
inversion
If True, the resulting transformation will contain an inversion of the coordinate system,
resulting in a rotoinversion (improper rotation).
Returns
-------
rotation
Object containing the rotations represented by the rotation vectors.
"""
rotvec_ = torch.as_tensor(rotvec)
reflection_ = torch.as_tensor(reflection)
inversion_ = torch.as_tensor(inversion)
if rotvec_.is_complex():
raise ValueError('rotvec should be real numbers')
if not rotvec_.is_floating_point():
# integer or boolean dtypes
rotvec_ = rotvec_.float()
if degrees:
rotvec_ = torch.deg2rad(rotvec_)
if rotvec_.shape[-1] != 3:
raise ValueError(f'Expected `rot_vec` to have shape (..., 3), got {rotvec_.shape}')
angles = torch.linalg.vector_norm(rotvec_, dim=-1, keepdim=True)
scales = torch.special.sinc(angles / (2 * torch.pi)) / 2
quaternions = torch.cat((scales * rotvec_, torch.cos(angles / 2)), -1)
if reflection_.any():
# we can do it here and avoid the extra of converting to quaternions,
# back to axis-angle and then to quaternions.
inversion_ = reflection_ ^ inversion_
scales = torch.cos(0.5 * angles) / angles
reflected_quaternions = torch.cat((scales * rotvec_, -torch.sin(angles / 2)), -1)
quaternions = torch.where(reflection_, reflected_quaternions, quaternions)
return cls(quaternions, normalize=False, copy=False, inversion=inversion_, reflection=False)
@classmethod
def from_euler(
cls,
seq: str,
angles: torch.Tensor | NestedSequence[float] | float,
degrees: bool = False,
inversion: torch.Tensor | NestedSequence[bool] | bool = False,
reflection: torch.Tensor | NestedSequence[bool] | bool = False,
) -> Self:
"""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 centered frame of reference (intrinsic), which
is attached to, and moves with, the object under rotation [EULa]_.
Parameters
----------
seq
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
(..., [1 or 2 or 3]), matching the number of axes in seq.
Euler angles specified in radians (`degrees` is False) or degrees
(`degrees` is True).
degrees
If True, then the given angles are assumed to be in degrees.
Otherwise they are assumed to be in radians
inversion
If True, the resulting transformation will contain an inversion of the coordinate system,
resulting in a rotoinversion (improper rotation).
reflection
If True, the resulting transformation will contain a reflection
about a plane perpendicular to the rotation axis, resulting in an
improper rotation.
Returns
-------
rotation
Object containing the rotation represented by the sequence of
rotations around given axes with given angles.
References
----------
.. [EULa] Euler angles https://en.wikipedia.org/wiki/Euler_angles#Definition_by_intrinsic_rotations
"""
n_axes = len(seq)
if n_axes < 1 or n_axes > 3:
raise ValueError('Expected axis specification to be a non-empty ' f'string of upto 3 characters, got {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', " f"'z'] or ['X', 'Y', 'Z'], got {seq}")
if any(seq[i] == seq[i + 1] for i in range(n_axes - 1)):
raise ValueError('Expected consecutive axes to be different, ' f'got {seq}')
seq = seq.lower()
angles = torch.as_tensor(angles)
if degrees:
angles = torch.deg2rad(angles)
if n_axes == 1 and angles.ndim == 0:
angles = angles.reshape((1, 1))
is_single = True
elif angles.ndim == 1:
angles = angles[None, :]
is_single = True
else:
is_single = False
if angles.ndim < 2 or angles.shape[-1] != n_axes:
raise ValueError('Expected angles to have shape (..., ' f'n_axes), got {angles.shape}.')
quaternions = _make_elementary_quat(seq[0], angles[..., 0])
for axis, angle in zip(seq[1:], angles[..., 1:].unbind(-1), strict=False):
if intrinsic:
quaternions = _compose_quaternions(quaternions, _make_elementary_quat(axis, angle))
else:
quaternions = _compose_quaternions(_make_elementary_quat(axis, angle), quaternions)
if is_single:
return cls(quaternions[0], normalize=False, copy=False, inversion=inversion, reflection=reflection)
else:
return cls(quaternions, normalize=False, copy=False, inversion=inversion, reflection=reflection)
@classmethod
def from_davenport(cls, axes: torch.Tensor, order: str, angles: torch.Tensor, degrees: bool = False):
"""Not implemented."""
raise NotImplementedError
@classmethod
def from_mrp(cls, mrp: torch.Tensor) -> Self:
"""Not implemented."""
raise NotImplementedError
@overload
def as_quat(
self, canonical: bool = ..., *, improper: Literal['warn'] | Literal['ignore'] = 'warn'
) -> torch.Tensor: ...
@overload
def as_quat(
self, canonical: bool = ..., *, improper: Literal['reflection'] | Literal['inversion']
) -> tuple[torch.Tensor, torch.Tensor]: ...
def as_quat(
self,
canonical: bool = False,
*,
improper: Literal['reflection'] | Literal['inversion'] | Literal['ignore'] | Literal['warn'] = 'warn',
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
"""Represent as quaternions.
Active rotations in 3 dimensions can be represented using unit norm
quaternions [QUAb]_. The mapping from quaternions to rotations is
two-to-one, i.e. quaternions ``q`` and ``-q``, where ``-q`` simply
reverses the sign of each component, represent the same spatial
rotation. The returned value is in scalar-last (x, y, z, w) format.
Parameters
----------
canonical
Whether to map the redundant double cover of rotation space to a
unique "canonical" single cover. If True, then the quaternion is
chosen from {q, -q} such that the w term is positive. If the w term
is 0, then the quaternion is chosen such that the first nonzero
term of the x, y, and z terms is positive.
improper
How to handle improper rotations. If 'warn', a warning is raised if
the rotation is improper. If 'ignore', the reflection information is
discarded. If 'reflection' or 'inversion', additional information is
returned in the form of a boolean tensor indicating if the rotation
is improper.
If 'reflection', the boolean tensor indicates if the rotation contains
a reflection about a plane perpendicular to the rotation axis.
Note that this required additional computation.
If 'inversion', the boolean tensor indicates if the rotation contains
an inversion of the coordinate system.
The quaternion is adjusted to represent the rotation to be performed
before the reflection or inversion.
Returns
-------
quaternions
shape (..., 4,), depends on shape of inputs used for initialization.
(optional) reflection (if improper is 'reflection') or inversion (if improper is 'inversion')
boolean tensor of shape (...,), indicating if the rotation is improper
and if a reflection or inversion should be performed after the rotation.
References
----------
.. [QUAb] Quaternions https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation
"""
quaternions: torch.Tensor = self._quaternions
is_improper: torch.Tensor = self._is_improper
if improper == 'warn':
if is_improper.any():
warnings.warn(
'Rotation contains improper rotations. Set `improper="reflection"` or `improper="inversion"` '
'to get reflection or inversion information.',
stacklevel=2,
)
elif improper == 'ignore' or improper == 'inversion':
...
elif improper == 'reflection':
axis, angle = _quaternion_to_axis_angle(quaternions)
angle = (angle + torch.pi * is_improper.float()).unsqueeze(-1)
quaternions = torch.cat((torch.sin(angle / 2) * axis, torch.cos(angle / 2)), -1)
else:
raise ValueError(f'Invalid improper value: {improper}')
if self.single:
quaternions = quaternions[0]
is_improper = is_improper[0]
if canonical:
quaternions = _canonical_quaternion(quaternions)
else:
quaternions = quaternions.clone()
if improper == 'reflection' or improper == 'inversion':
return quaternions, is_improper
else:
return quaternions
def as_matrix(self) -> torch.Tensor:
"""Represent as rotation matrix.
3D rotations can be represented using rotation matrices, which
are 3 x 3 real orthogonal matrices with determinant equal to +1 [ROTb]_
for proper rotations and -1 for improper rotations.
Returns
-------
matrix
shape (..., 3, 3), depends on shape of inputs used for initialization.
References
----------
.. [ROTb] Rotation matrix https://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions
"""
quaternions = self._quaternions
matrix = _quaternion_to_matrix(quaternions)
if self._is_improper.any():
matrix = matrix * self.det.unsqueeze(-1).unsqueeze(-1)
if self._single:
return matrix[0]
else:
return matrix
@overload
def as_rotvec(
self, degrees: bool = ..., *, improper: Literal['ignore'] | Literal['warn'] = 'warn'
) -> torch.Tensor: ...
@overload
def as_rotvec(
self, degrees: bool = ..., *, improper: Literal['reflection'] | Literal['inversion']
) -> tuple[torch.Tensor, torch.Tensor]: ...
def as_rotvec(
self,
degrees: bool = False,
improper: Literal['reflection'] | Literal['inversion'] | Literal['ignore'] | Literal['warn'] = 'warn',
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
"""Represent as 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 [ROTc]_.
Parameters
----------
degrees
Returned magnitudes are in degrees if this flag is True, else they are in radians
improper
How to handle improper rotations. If 'warn', a warning is raised if
the rotation is improper. If 'ignore', the reflection information is
discarded. If 'reflection' or 'inversion', additional information is
returned in the form of a boolean tensor indicating if the rotation
is improper.
If 'reflection', the boolean tensor indicates if the rotation contains
a reflection about a plane perpendicular to the rotation axis.
If 'inversion', the boolean tensor indicates if the rotation contains
an inversion of the coordinate system.
The quaternion is adjusted to represent the rotation to be performed
before the reflection or inversion.
Returns
-------
rotvec
Shape (..., 3), depends on shape of inputs used for initialization.
(optional) reflection (if improper is 'reflection') or inversion (if improper is 'inversion')
boolean tensor of shape (...,), indicating if the rotation is improper
and if a reflection or inversion should be performed after the rotation.
References
----------
.. [ROTc] Rotation vector https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation#Rotation_vector
"""
if improper == 'reflection' or improper == 'inversion':
quaternions, is_improper = self.as_quat(canonical=True, improper=improper)
else:
quaternions, is_improper = self.as_quat(canonical=True, improper=improper), None
angles = 2 * torch.atan2(torch.linalg.vector_norm(quaternions[..., :3], dim=-1), quaternions[..., 3])
scales = 2 / (torch.special.sinc(angles / (2 * torch.pi)))
rotvec = scales[..., None] * quaternions[..., :3]
if degrees:
rotvec = torch.rad2deg(rotvec)
if is_improper is not None:
return rotvec, is_improper
else:
return rotvec
@overload
def as_euler(
self,
seq: str,
degrees: bool = ...,
*,
improper: Literal['ignore'] | Literal['warn'] = 'warn',