-
Notifications
You must be signed in to change notification settings - Fork 239
/
special_orthogonal.py
1917 lines (1552 loc) · 63.4 KB
/
special_orthogonal.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
"""Exposes the `SpecialOrthogonal` group class."""
import geomstats.backend as gs
import geomstats.errors
import geomstats.vectorization
from geomstats import algebra_utils
from geomstats.geometry.general_linear import GeneralLinear
from geomstats.geometry.invariant_metric import BiInvariantMetric
from geomstats.geometry.lie_group import LieGroup
from geomstats.geometry.skew_symmetric_matrices import SkewSymmetricMatrices
from geomstats.geometry.symmetric_matrices import SymmetricMatrices
ATOL = 1e-5
TAYLOR_COEFFS_1_AT_0 = [1., 0.,
- 1. / 12., 0.,
- 1. / 720., 0.,
- 1. / 30240., 0.]
TAYLOR_COEFFS_2_AT_0 = [1. / 12., 0.,
1. / 720., 0.,
1. / 30240., 0.,
1. / 1209600., 0.]
TAYLOR_COEFFS_1_AT_PI = [0., - gs.pi / 4.,
- 1. / 4., - gs.pi / 48.,
- 1. / 48., - gs.pi / 480.,
- 1. / 480.]
class _SpecialOrthogonalMatrices(GeneralLinear, LieGroup):
"""Class for special orthogonal groups in matrix representation.
Parameters
----------
n : int
Integer representing the shape of the matrices: n x n.
"""
def __init__(self, n):
super(_SpecialOrthogonalMatrices, self).__init__(
dim=int((n * (n - 1)) / 2), default_point_type='matrix', n=n)
self.lie_algebra = SkewSymmetricMatrices(n=n)
self.bi_invariant_metric = BiInvariantMetric(group=self)
def belongs(self, point, atol=ATOL):
"""Check whether point is an orthogonal matrix.
Parameters
----------
point : array-like, shape=[..., n, n]
Point to check.
atol : float
Absolute tolerance to check equality of the transpose and the
inverse of point.
Optional, default: 1e-5.
Returns
-------
belongs : array-like, shape=[...,]
Boolean evaluating if point belongs to SO(n).
"""
return self.equal(
self.mul(point, self.transpose(point)), self.identity, atol=atol)
@classmethod
def inverse(cls, point):
"""Return the transpose matrix of point.
Parameters
----------
point : array-like, shape=[..., n, n]
Point in SO(n).
Returns
-------
inverse : array-like, shape=[..., n, n]
Inverse.
"""
return cls.transpose(point)
@classmethod
def projection(cls, point):
"""Project a matrix on SO(n) by minimizing the Frobenius norm.
Parameters
----------
point : array-like, shape=[..., n, n]
Matrix.
Returns
-------
rot_mat : array-like, shape=[..., n, n]
Rotation matrix.
"""
aux_mat = cls.mul(cls.transpose(point), point)
inv_sqrt_mat = SymmetricMatrices.powerm(aux_mat, - 1 / 2)
rot_mat = cls.mul(point, inv_sqrt_mat)
return rot_mat
def _is_in_lie_algebra(self, tangent_vec, atol=ATOL):
return self.lie_algebra.belongs(tangent_vec, atol=atol)
@classmethod
def _to_lie_algebra(cls, vec):
"""Project vector onto skew-symmetric matrices.
Parameters
----------
vec : array-like, shape=[..., n, n]
Vector.
Returns
-------
tangent_vec : array-like, shape=[..., n, n]
Tangent vector at base point.
"""
return cls.to_skew_symmetric(vec)
def random_uniform(self, n_samples=1, tol=1e-6):
"""Sample in SO(n) from the uniform distribution.
Parameters
----------
n_samples : int
Number of samples.
Optional, default: 1.
tol : unused
Returns
-------
samples : array-like, shape=[..., n, n]
Points sampled on the SO(n).
"""
if n_samples == 1:
random_mat = gs.random.rand(self.n, self.n)
else:
random_mat = gs.random.rand(n_samples, self.n, self.n)
skew = self.to_tangent(random_mat)
return self.exp(skew)
class _SpecialOrthogonal3Vectors(LieGroup):
"""Class for the special orthogonal group SO(3) in vector representation.
i.e. the Lie group of rotations. This class is specific to the vector
representation of rotations. For the matrix representation use the
SpecialOrthogonal class and set `n=3`.
Parameters
----------
epsilon : float
Precision to use for calculations involving potential divison by 0 in
rotations.
Optional, default: 0.
"""
def __init__(self, epsilon=0.):
LieGroup.__init__(
self, dim=3, default_point_type='vector')
self.n = 3
self.epsilon = epsilon
self.bi_invariant_metric = BiInvariantMetric(group=self)
def get_identity(self, point_type='vector'):
"""Get the identity of the group.
Parameters
----------
point_type : str, {'vector', 'matrix'}
Point_type of the returned value. Unused here.
Returns
-------
identity : array-like, shape=[3,]
Identity.
"""
identity = gs.zeros(self.dim)
if point_type == 'matrix':
identity = gs.eye(self.n)
return identity
identity = property(get_identity)
def belongs(self, point, atol=ATOL):
"""Evaluate if a point belongs to SO(3).
Parameters
----------
point : array-like, shape=[..., 3]
Point to check whether it belongs to SO(3).
atol : unused
Returns
-------
belongs : array-like, shape=[...,]
Boolean indicating whether point belongs to SO(3).
"""
vec_dim = point.shape[-1]
belongs = vec_dim == self.dim
if point.ndim == 2:
belongs = gs.tile([belongs], (point.shape[0],))
return belongs
def regularize(self, point):
"""Regularize a point to be in accordance with convention.
In 3D, regularize the norm of the rotation vector,
to be between 0 and pi, following the axis-angle
representation's convention.
If the angle angle is between pi and 2pi,
the function computes its complementary in 2pi and
inverts the direction of the rotation axis.
Parameters
----------
point : array-like, shape=[...,3]
Point.
Returns
-------
regularized_point : array-like, shape=[..., 3]
Regularized point.
"""
regularized_point = point
angle = gs.linalg.norm(regularized_point, axis=-1)
mask_0 = gs.isclose(angle, 0.)
mask_not_0 = ~mask_0
mask_pi = gs.isclose(angle, gs.pi)
# This avoids division by 0.
mask_0_float = gs.cast(mask_0, gs.float32) + self.epsilon
mask_not_0_float = (
gs.cast(mask_not_0, gs.float32)
+ self.epsilon)
mask_pi_float = gs.cast(mask_pi, gs.float32) + self.epsilon
k = gs.floor(angle / (2 * gs.pi) + .5)
angle += mask_0_float
norms_ratio = gs.zeros_like(angle)
norms_ratio += mask_not_0_float * (
1. - 2. * gs.pi * k / angle)
norms_ratio += mask_0_float
norms_ratio += mask_pi_float * (
gs.pi / angle
- (1. - 2. * gs.pi * k / angle))
regularized_point = gs.einsum(
'...,...i->...i', norms_ratio, regularized_point)
return regularized_point
@geomstats.vectorization.decorator(
['else', 'vector', 'else', 'output_point'])
def regularize_tangent_vec_at_identity(
self, tangent_vec, metric=None):
"""Regularize a tangent vector at the identity.
In 3D, regularize a tangent_vector by getting its norm at the identity,
determined by the metric, to be less than pi.
Parameters
----------
tangent_vec : array-like, shape=[..., 3]
Tangent vector at base point.
metric : RiemannianMetric
Metric.
Optional, default: self.left_canonical_metric.
Returns
-------
regularized_vec : array-like, shape=[..., 3]
Regularized tangent vector.
"""
if metric is None:
metric = self.left_canonical_metric
tangent_vec_metric_norm = metric.norm(tangent_vec)
tangent_vec_canonical_norm = gs.linalg.norm(tangent_vec, axis=-1)
mask_norm_0 = gs.isclose(tangent_vec_metric_norm, 0.)
mask_canonical_norm_0 = gs.isclose(tangent_vec_canonical_norm, 0.)
mask_0 = mask_norm_0 | mask_canonical_norm_0
mask_else = ~mask_0
# This avoids division by 0.
mask_0_float = gs.cast(mask_0, gs.float32) + self.epsilon
mask_else_float = gs.cast(mask_else, gs.float32) + self.epsilon
regularized_vec = gs.zeros_like(tangent_vec)
regularized_vec += gs.einsum(
'...,...i->...i', mask_0_float, tangent_vec)
tangent_vec_canonical_norm += mask_0_float
coef = gs.zeros_like(tangent_vec_metric_norm)
coef += mask_else_float * (
tangent_vec_metric_norm
/ tangent_vec_canonical_norm)
coef_tangent_vec = gs.einsum(
'...,...i->...i', coef, tangent_vec)
regularized_vec += gs.einsum(
'...,...i->...i',
mask_else_float,
self.regularize(coef_tangent_vec))
coef += mask_0_float
regularized_vec = gs.einsum(
'...,...i->...i', 1. / coef, regularized_vec)
regularized_vec = gs.einsum(
'...,...i->...i', mask_else_float, regularized_vec)
return regularized_vec
@geomstats.vectorization.decorator(
['else', 'vector', 'vector', 'else', 'output_point'])
def regularize_tangent_vec(
self, tangent_vec, base_point, metric=None):
"""Regularize tangent vector at a base point.
In 3D, regularize a tangent_vector by getting the norm of its parallel
transport to the identity, determined by the metric, less than pi.
Parameters
----------
tangent_vec : array-like, shape=[...,3]
Tangent vector at base point.
base_point : array-like, shape=[..., 3]
Point on the manifold.
metric : RiemannianMetric
Metric.
Optional, default: self.left_canonical_metric.
Returns
-------
regularized_tangent_vec : array-like, shape=[..., 3]
Regularized tangent vector.
"""
if metric is None:
metric = self.left_canonical_metric
base_point = self.regularize(base_point)
tangent_vec_at_id = self.tangent_translation_map(
base_point, left_or_right=metric.left_or_right, inverse=True)(
tangent_vec
)
tangent_vec_at_id = self.regularize_tangent_vec_at_identity(
tangent_vec_at_id, metric)
regularized_tangent_vec = self.tangent_translation_map(
base_point, left_or_right=metric.left_or_right)(tangent_vec_at_id)
return regularized_tangent_vec
@geomstats.vectorization.decorator(['else', 'matrix'])
def projection(self, point):
"""Project a matrix on SO(3) using the Frobenius norm.
Parameters
----------
point : array-like, shape=[..., n, n]
Matrix.
Returns
-------
rot_mat : array-like, shape=[..., n, n]
Rotation matrix.
"""
mat = point
n_mats, _, _ = mat.shape
mat_unitary_u, _, mat_unitary_v = gs.linalg.svd(mat)
rot_mat = gs.einsum('nij,njk->nik', mat_unitary_u, mat_unitary_v)
mask = gs.less(gs.linalg.det(rot_mat), 0.)
mask_float = gs.cast(mask, gs.float32) + self.epsilon
diag = gs.array([[1., 1., -1.]])
diag = gs.to_ndarray(
algebra_utils.from_vector_to_diagonal_matrix(diag),
to_ndim=3) + self.epsilon
new_mat_diag_s = gs.tile(diag, [n_mats, 1, 1])
aux_mat = gs.einsum(
'nij,njk->nik', mat_unitary_u, new_mat_diag_s)
rot_mat += gs.einsum(
'n,njk->njk', mask_float,
gs.einsum('nij,njk->nik', aux_mat, mat_unitary_v))
return rot_mat
@geomstats.vectorization.decorator(['else', 'vector'])
def skew_matrix_from_vector(self, vec):
"""Get the skew-symmetric matrix derived from the vector.
In 3D, compute the skew-symmetric matrix,known as the cross-product of
a vector, associated to the vector `vec`.
In nD, fill a skew-symmetric matrix with the values of the vector.
Parameters
----------
vec : array-like, shape=[..., dim]
Vector.
Returns
-------
skew_mat : array-like, shape=[..., n, n]
Skew-symmetric matrix.
"""
n_vecs, vec_dim = gs.shape(vec)
if self.n == 2:
vec = gs.tile(vec, [1, 2])
vec = gs.reshape(vec, (n_vecs, 2))
id_skew = gs.array(
gs.tile([[[0., 1.], [-1., 0.]]], (n_vecs, 1, 1)))
skew_mat = gs.einsum(
'...ij,...i->...ij', gs.cast(id_skew, gs.float32), vec)
elif self.n == 3:
levi_civita_symbol = gs.tile([[
[[0., 0., 0.],
[0., 0., 1.],
[0., -1., 0.]],
[[0., 0., -1.],
[0., 0., 0.],
[1., 0., 0.]],
[[0., 1., 0.],
[-1., 0., 0.],
[0., 0., 0.]]
]], (n_vecs, 1, 1, 1))
levi_civita_symbol = gs.array(levi_civita_symbol)
levi_civita_symbol += self.epsilon
# This avoids dividing by 0.
basis_vec_1 = gs.array(
gs.tile([[1., 0., 0.]], (n_vecs, 1))) + self.epsilon
basis_vec_2 = gs.array(
gs.tile([[0., 1., 0.]], (n_vecs, 1))) + self.epsilon
basis_vec_3 = gs.array(
gs.tile([[0., 0., 1.]], (n_vecs, 1))) + self.epsilon
cross_prod_1 = gs.einsum(
'nijk,ni,nj->nk',
levi_civita_symbol,
basis_vec_1,
vec)
cross_prod_2 = gs.einsum(
'nijk,ni,nj->nk',
levi_civita_symbol,
basis_vec_2,
vec)
cross_prod_3 = gs.einsum(
'nijk,ni,nj->nk',
levi_civita_symbol,
basis_vec_3,
vec)
cross_prod_1 = gs.to_ndarray(cross_prod_1, to_ndim=3, axis=1)
cross_prod_2 = gs.to_ndarray(cross_prod_2, to_ndim=3, axis=1)
cross_prod_3 = gs.to_ndarray(cross_prod_3, to_ndim=3, axis=1)
skew_mat = gs.concatenate(
[cross_prod_1, cross_prod_2, cross_prod_3], axis=1)
else: # SO(n)
mat_dim = gs.cast(
((1. + gs.sqrt(1. + 8. * vec_dim)) / 2.), gs.int32)
skew_mat = gs.zeros((n_vecs,) + (self.n,) * 2)
upper_triangle_indices = gs.triu_indices(mat_dim, k=1)
for i in range(n_vecs):
skew_mat[i][upper_triangle_indices] = vec[i]
skew_mat[i] = skew_mat[i] - gs.transpose(skew_mat[i])
return skew_mat
@geomstats.vectorization.decorator(['else', 'matrix', 'output_point'])
def vector_from_skew_matrix(self, skew_mat):
"""Derive a vector from the skew-symmetric matrix.
In 3D, compute the vector defining the cross product
associated to the skew-symmetric matrix skew mat.
Parameters
----------
skew_mat : array-like, shape=[..., n, n]
Skew-symmetric matrix.
Returns
-------
vec : array-like, shape=[..., dim]
Vector.
"""
n_skew_mats, _, _ = skew_mat.shape
vec_dim = self.dim
vec = gs.zeros((n_skew_mats, vec_dim))
if self.n == 2: # SO(2)
vec = skew_mat[:, 0, 1]
vec = gs.expand_dims(vec, axis=1)
elif self.n == 3: # SO(3)
vec_1 = gs.to_ndarray(skew_mat[:, 2, 1], to_ndim=2, axis=1)
vec_2 = gs.to_ndarray(skew_mat[:, 0, 2], to_ndim=2, axis=1)
vec_3 = gs.to_ndarray(skew_mat[:, 1, 0], to_ndim=2, axis=1)
vec = gs.concatenate([vec_1, vec_2, vec_3], axis=1)
return vec
@geomstats.vectorization.decorator(['else', 'matrix', 'output_point'])
def rotation_vector_from_matrix(self, rot_mat):
r"""Convert rotation matrix (in 3D) to rotation vector (axis-angle).
Get the angle through the trace of the rotation matrix:
The eigenvalues are:
:math:`\{1, \cos(angle) + i \sin(angle), \cos(angle) - i \sin(angle)\}`
so that:
:math:`trace = 1 + 2 \cos(angle), \{-1 \leq trace \leq 3\}`
Get the rotation vector through the formula:
:math:`S_r = \frac{angle}{(2 * \sin(angle) ) (R - R^T)}`
For the edge case where the angle is close to pi,
the formulation is derived by using the following equality (see the
Axis-angle representation on Wikipedia):
:math:`outer(r, r) = \frac{1}{2} (R + I_3)`
In nD, the rotation vector stores the :math:`n(n-1)/2` values
of the skew-symmetric matrix representing the rotation.
Parameters
----------
rot_mat : array-like, shape=[..., n, n]
Rotation matrix.
Returns
-------
regularized_rot_vec : array-like, shape=[..., 3]
Rotation vector.
"""
n_rot_mats, _, _ = rot_mat.shape
trace = gs.trace(rot_mat, axis1=1, axis2=2)
trace = gs.to_ndarray(trace, to_ndim=2, axis=1)
trace_num = gs.clip(trace, -1, 3)
angle = gs.arccos(0.5 * (trace_num - 1))
rot_mat_transpose = gs.transpose(rot_mat, axes=(0, 2, 1))
rot_vec_not_pi = self.vector_from_skew_matrix(
rot_mat - rot_mat_transpose)
mask_0 = gs.cast(gs.isclose(angle, 0.), gs.float32)
mask_pi = gs.cast(gs.isclose(angle, gs.pi, atol=1e-2), gs.float32)
mask_else = (1 - mask_0) * (1 - mask_pi)
numerator = 0.5 * mask_0 + angle * mask_else
denominator = (1 - angle ** 2 / 6) * mask_0 + 2 * gs.sin(
angle) * mask_else + mask_pi
rot_vec_not_pi = rot_vec_not_pi * numerator / denominator
vector_outer = 0.5 * (gs.eye(3) + rot_mat)
gs.set_diag(
vector_outer, gs.maximum(
0., gs.diagonal(vector_outer, axis1=1, axis2=2)))
squared_diag_comp = gs.diagonal(vector_outer, axis1=1, axis2=2)
diag_comp = gs.sqrt(squared_diag_comp)
norm_line = gs.linalg.norm(vector_outer, axis=2)
max_line_index = gs.argmax(norm_line, axis=1)
selected_line = gs.get_slice(
vector_outer, (range(n_rot_mats), max_line_index))
signs = gs.sign(selected_line)
rot_vec_pi = angle * signs * diag_comp
rot_vec = rot_vec_not_pi + mask_pi * rot_vec_pi
return self.regularize(rot_vec)
@geomstats.vectorization.decorator(['else', 'vector'])
def matrix_from_rotation_vector(self, rot_vec):
"""Convert rotation vector to rotation matrix.
Parameters
----------
rot_vec: array-like, shape=[..., 3]
Rotation vector.
Returns
-------
rot_mat: array-like, shape=[..., 3]
Rotation matrix.
"""
rot_vec = self.regularize(rot_vec)
angle = gs.linalg.norm(rot_vec, axis=1)
angle = gs.to_ndarray(angle, to_ndim=2, axis=1)
skew_rot_vec = self.skew_matrix_from_vector(rot_vec)
coef_1 = gs.zeros_like(angle)
coef_2 = gs.zeros_like(angle)
# This avoids dividing by 0.
mask_0 = gs.isclose(angle, 0.)
mask_0_float = gs.cast(mask_0, gs.float32) + self.epsilon
coef_1 += mask_0_float * (1. - (angle ** 2) / 6.)
coef_2 += mask_0_float * (1. / 2. - angle ** 2)
# This avoids dividing by 0.
mask_else = ~mask_0
mask_else_float = gs.cast(mask_else, gs.float32) + self.epsilon
angle += mask_0_float
coef_1 += mask_else_float * (gs.sin(angle) / angle)
coef_2 += mask_else_float * (
(1. - gs.cos(angle)) / (angle ** 2))
coef_1 = gs.squeeze(coef_1, axis=1)
coef_2 = gs.squeeze(coef_2, axis=1)
term_1 = (gs.eye(self.dim)
+ gs.einsum('n,njk->njk', coef_1, skew_rot_vec))
squared_skew_rot_vec = gs.einsum(
'nij,njk->nik', skew_rot_vec, skew_rot_vec)
term_2 = gs.einsum('n,njk->njk', coef_2, squared_skew_rot_vec)
return term_1 + term_2
@geomstats.vectorization.decorator(['else', 'matrix'])
def quaternion_from_matrix(self, rot_mat):
"""Convert a rotation matrix into a unit quaternion.
Parameters
----------
rot_mat : array-like, shape=[..., 3, 3]
Rotation matrix.
Returns
-------
quaternion : array-like, shape=[..., 4]
Quaternion.
"""
rot_vec = self.rotation_vector_from_matrix(rot_mat)
quaternion = self.quaternion_from_rotation_vector(rot_vec)
return quaternion
@geomstats.vectorization.decorator(['else', 'vector'])
def quaternion_from_rotation_vector(self, rot_vec):
"""Convert a rotation vector into a unit quaternion.
Parameters
----------
rot_vec : array-like, shape=[..., 3]
Rotation vector.
Returns
-------
quaternion : array-like, shape=[..., 4]
Quaternion.
"""
rot_vec = self.regularize(rot_vec)
angle = gs.linalg.norm(rot_vec, axis=1)
angle = gs.to_ndarray(angle, to_ndim=2, axis=1)
mask_0 = gs.isclose(angle, 0.)
mask_not_0 = ~mask_0
rotation_axis = gs.divide(
rot_vec,
angle
* gs.cast(mask_not_0, gs.float32)
+ gs.cast(mask_0, gs.float32))
quaternion = gs.concatenate(
(gs.cos(angle / 2),
gs.sin(angle / 2) * rotation_axis[:]),
axis=1)
return quaternion
@geomstats.vectorization.decorator(['else', 'vector'])
def rotation_vector_from_quaternion(self, quaternion):
"""Convert a unit quaternion into a rotation vector.
Parameters
----------
quaternion : array-like, shape=[..., 4]
Quaternion.
Returns
-------
rot_vec : array-like, shape=[..., 3]
Rotation vector.
"""
cos_half_angle = quaternion[:, 0]
cos_half_angle = gs.clip(cos_half_angle, -1, 1)
half_angle = gs.arccos(cos_half_angle)
half_angle = gs.to_ndarray(half_angle, to_ndim=2, axis=1)
mask_0 = gs.isclose(half_angle, 0.)
mask_not_0 = ~mask_0
rotation_axis = gs.divide(
quaternion[:, 1:],
gs.sin(half_angle) *
gs.cast(mask_not_0, gs.float32)
+ gs.cast(mask_0, gs.float32))
rot_vec = gs.array(
2 * half_angle
* rotation_axis
* gs.cast(mask_not_0, gs.float32))
rot_vec = self.regularize(rot_vec)
return rot_vec
@geomstats.vectorization.decorator(['else', 'vector'])
def matrix_from_quaternion(self, quaternion):
"""Convert a unit quaternion into a rotation vector.
Parameters
----------
quaternion : array-like, shape=[..., 4]
Quaternion.
Returns
-------
rot_mat : array-like, shape=[..., 3]
Rotation matrix.
"""
n_quaternions, _ = quaternion.shape
w, x, y, z = gs.hsplit(quaternion, 4)
rot_mat = gs.zeros((n_quaternions,) + (self.n,) * 2)
for i in range(n_quaternions):
# TODO (nina): Vectorize by applying the composition of
# quaternions to the identity matrix
column_1 = [w[i] ** 2 + x[i] ** 2 - y[i] ** 2 - z[i] ** 2,
2 * x[i] * y[i] - 2 * w[i] * z[i],
2 * x[i] * z[i] + 2 * w[i] * y[i]]
column_2 = [2 * x[i] * y[i] + 2 * w[i] * z[i],
w[i] ** 2 - x[i] ** 2 + y[i] ** 2 - z[i] ** 2,
2 * y[i] * z[i] - 2 * w[i] * x[i]]
column_3 = [2 * x[i] * z[i] - 2 * w[i] * y[i],
2 * y[i] * z[i] + 2 * w[i] * x[i],
w[i] ** 2 - x[i] ** 2 - y[i] ** 2 + z[i] ** 2]
mask_i = gs.get_mask_i_float(i, n_quaternions)
rot_mat_i = gs.transpose(
gs.hstack([column_1, column_2, column_3]))
rot_mat_i = gs.to_ndarray(rot_mat_i, to_ndim=3)
rot_mat += gs.einsum('...,...ij->...ij', mask_i, rot_mat_i)
return rot_mat
@staticmethod
@geomstats.vectorization.decorator(['vector'])
def matrix_from_tait_bryan_angles_extrinsic_xyz(tait_bryan_angles):
"""Convert Tait-Bryan angles to rot mat in extrensic coords (xyz).
Convert a rotation given in terms of the tait bryan angles,
[angle_1, angle_2, angle_3] in extrinsic (fixed) coordinate system
in order xyz, into a rotation matrix.
rot_mat = Z(angle_1).Y(angle_2).X(angle_3)
where:
- Z(angle_1) is a rotation of angle angle_1 around axis z.
- Y(angle_2) is a rotation of angle angle_2 around axis y.
- X(angle_3) is a rotation of angle angle_3 around axis x.
Parameters
----------
tait_bryan_angles : array-like, shape=[..., 3]
Returns
-------
rot_mat : array-like, shape=[..., 3, 3]
"""
n_tait_bryan_angles, _ = tait_bryan_angles.shape
rot_mat = []
angle_1 = tait_bryan_angles[:, 0]
angle_2 = tait_bryan_angles[:, 1]
angle_3 = tait_bryan_angles[:, 2]
# TODO: avoid for loop in vectorization of tait bryan angles
for i in range(n_tait_bryan_angles):
cos_angle_1 = gs.cos(angle_1[i])
sin_angle_1 = gs.sin(angle_1[i])
cos_angle_2 = gs.cos(angle_2[i])
sin_angle_2 = gs.sin(angle_2[i])
cos_angle_3 = gs.cos(angle_3[i])
sin_angle_3 = gs.sin(angle_3[i])
column_1 = [[cos_angle_1 * cos_angle_2],
[cos_angle_2 * sin_angle_1],
[- sin_angle_2]]
column_2 = [[(cos_angle_1 * sin_angle_2 * sin_angle_3
- cos_angle_3 * sin_angle_1)],
[(cos_angle_1 * cos_angle_3
+ sin_angle_1 * sin_angle_2 * sin_angle_3)],
[cos_angle_2 * sin_angle_3]]
column_3 = [[(sin_angle_1 * sin_angle_3
+ cos_angle_1 * cos_angle_3 * sin_angle_2)],
[(cos_angle_3 * sin_angle_1 * sin_angle_2
- cos_angle_1 * sin_angle_3)],
[cos_angle_2 * cos_angle_3]]
rot_mat.append(gs.hstack((column_1, column_2, column_3)))
return gs.stack(rot_mat)
@staticmethod
@geomstats.vectorization.decorator(['vector'])
def matrix_from_tait_bryan_angles_extrinsic_zyx(tait_bryan_angles):
"""Convert Tait-Bryan angles to rot mat in extrensic coords (zyx).
Convert a rotation given in terms of the tait bryan angles,
[angle_1, angle_2, angle_3] in extrinsic (fixed) coordinate system
in order zyx, into a rotation matrix.
rot_mat = X(angle_1).Y(angle_2).Z(angle_3)
where:
- X(angle_1) is a rotation of angle angle_1 around axis x.
- Y(angle_2) is a rotation of angle angle_2 around axis y.
- Z(angle_3) is a rotation of angle angle_3 around axis z.
Parameters
----------
tait_bryan_angles : array-like, shape=[..., 3]
Returns
-------
rot_mat : array-like, shape=[..., n, n]
"""
n_tait_bryan_angles, _ = tait_bryan_angles.shape
rot_mat = []
angle_1 = tait_bryan_angles[:, 0]
angle_2 = tait_bryan_angles[:, 1]
angle_3 = tait_bryan_angles[:, 2]
for i in range(n_tait_bryan_angles):
cos_angle_1 = gs.cos(angle_1[i])
sin_angle_1 = gs.sin(angle_1[i])
cos_angle_2 = gs.cos(angle_2[i])
sin_angle_2 = gs.sin(angle_2[i])
cos_angle_3 = gs.cos(angle_3[i])
sin_angle_3 = gs.sin(angle_3[i])
column_1 = [[cos_angle_2 * cos_angle_3],
[(cos_angle_1 * sin_angle_3
+ cos_angle_3 * sin_angle_1 * sin_angle_2)],
[(sin_angle_1 * sin_angle_3
- cos_angle_1 * cos_angle_3 * sin_angle_2)]]
column_2 = [[- cos_angle_2 * sin_angle_3],
[(cos_angle_1 * cos_angle_3
- sin_angle_1 * sin_angle_2 * sin_angle_3)],
[(cos_angle_3 * sin_angle_1
+ cos_angle_1 * sin_angle_2 * sin_angle_3)]]
column_3 = [[sin_angle_2],
[- cos_angle_2 * sin_angle_1],
[cos_angle_1 * cos_angle_2]]
rot_mat.append(gs.hstack((column_1, column_2, column_3)))
return gs.stack(rot_mat)
@geomstats.vectorization.decorator(['else', 'vector', 'else', 'else'])
def matrix_from_tait_bryan_angles(self, tait_bryan_angles,
extrinsic_or_intrinsic='extrinsic',
order='zyx'):
"""Convert Tait-Bryan angles to rot mat in extr or intr coords.
Convert a rotation given in terms of the tait bryan angles,
[angle_1, angle_2, angle_3] in extrinsic (fixed) or
intrinsic (moving) coordinate frame into a rotation matrix.
If the order is zyx, into the rotation matrix rot_mat:
rot_mat = X(angle_1).Y(angle_2).Z(angle_3)
where:
- X(angle_1) is a rotation of angle angle_1 around axis x.
- Y(angle_2) is a rotation of angle angle_2 around axis y.
- Z(angle_3) is a rotation of angle angle_3 around axis z.
Exchanging 'extrinsic' and 'intrinsic' amounts to
exchanging the order.
Parameters
----------
tait_bryan_angles : array-like, shape=[..., 3]
extrinsic_or_intrinsic : str, {'extrensic', 'intrinsic'} optional
default: 'extrinsic'
order : str, {'xyz', 'zyx'}, optional
default: 'zyx'
Returns
-------
rot_mat : array-like, shape=[..., n, n]
"""
geomstats.errors.check_parameter_accepted_values(
extrinsic_or_intrinsic,
'extrinsic_or_intrinsic',
['extrinsic', 'intrinsic'])
geomstats.errors.check_parameter_accepted_values(
order,
'order',
['xyz', 'zyx'])
tait_bryan_angles = gs.to_ndarray(tait_bryan_angles, to_ndim=2)
extrinsic_zyx = (extrinsic_or_intrinsic == 'extrinsic'
and order == 'zyx')
intrinsic_xyz = (extrinsic_or_intrinsic == 'intrinsic'
and order == 'xyz')
extrinsic_xyz = (extrinsic_or_intrinsic == 'extrinsic'
and order == 'xyz')
intrinsic_zyx = (extrinsic_or_intrinsic == 'intrinsic'
and order == 'zyx')
if extrinsic_zyx:
rot_mat = self.matrix_from_tait_bryan_angles_extrinsic_zyx(
tait_bryan_angles)
elif intrinsic_xyz:
tait_bryan_angles_reversed = gs.flip(tait_bryan_angles, axis=1)
rot_mat = self.matrix_from_tait_bryan_angles_extrinsic_zyx(
tait_bryan_angles_reversed)
elif extrinsic_xyz:
rot_mat = self.matrix_from_tait_bryan_angles_extrinsic_xyz(
tait_bryan_angles)
elif intrinsic_zyx:
tait_bryan_angles_reversed = gs.flip(tait_bryan_angles, axis=1)
rot_mat = self.matrix_from_tait_bryan_angles_extrinsic_xyz(
tait_bryan_angles_reversed)
else:
raise ValueError('extrinsic_or_intrinsic should be'
' \'extrinsic\' or \'intrinsic\''
' and order should be \'xyz\' or \'zyx\'.')
return rot_mat
@geomstats.vectorization.decorator(['else', 'matrix', 'else', 'else'])
def tait_bryan_angles_from_matrix(self, rot_mat,
extrinsic_or_intrinsic='extrinsic',
order='zyx'):
"""Convert rot_mat into Tait-Bryan angles.
Convert a rotation matrix rot_mat into the tait bryan angles,
[angle_1, angle_2, angle_3] in extrinsic (fixed) coordinate frame,
for the order zyx, i.e.:
rot_mat = X(angle_1).Y(angle_2).Z(angle_3)
where:
- X(angle_1) is a rotation of angle angle_1 around axis x.
- Y(angle_2) is a rotation of angle angle_2 around axis y.
- Z(angle_3) is a rotation of angle angle_3 around axis z.
Parameters
----------
rot_mat : array-like, shape=[..., n, n]
extrinsic_or_intrinsic : str, {'extrinsic', 'intrinsic'}, optional
default: 'extrinsic'
order : str, {'xyz', 'zyx'}, optional
default: 'zyx'
Returns
-------
tait_bryan_angles : array-like, shape=[..., 3]
"""
quaternion = self.quaternion_from_matrix(rot_mat)
tait_bryan_angles = self.tait_bryan_angles_from_quaternion(
quaternion,
extrinsic_or_intrinsic=extrinsic_or_intrinsic,
order=order)
return tait_bryan_angles
@geomstats.vectorization.decorator(['else', 'vector'])
def quaternion_from_tait_bryan_angles_intrinsic_xyz(
self, tait_bryan_angles):
"""Convert Tait-Bryan angles to into unit quaternion.
Convert a rotation given by Tait-Bryan angles in extrinsic
coordinate systems and order xyz into a unit quaternion.
Parameters
----------
tait_bryan_angles : array-like, shape=[..., 3]
Returns