-
Notifications
You must be signed in to change notification settings - Fork 239
/
special_euclidean.py
1355 lines (1093 loc) · 45.1 KB
/
special_euclidean.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
"""The special Euclidean group SE(n).
i.e. the Lie group of rigid transformations in n dimensions.
"""
import geomstats.algebra_utils as utils
import geomstats.backend as gs
import geomstats.vectorization
from geomstats.geometry.base import LevelSet
from geomstats.geometry.euclidean import Euclidean
from geomstats.geometry.general_linear import GeneralLinear, Matrices
from geomstats.geometry.invariant_metric import InvariantMetric, _InvariantMetricMatrix
from geomstats.geometry.lie_algebra import MatrixLieAlgebra
from geomstats.geometry.lie_group import LieGroup, MatrixLieGroup
from geomstats.geometry.skew_symmetric_matrices import SkewSymmetricMatrices
from geomstats.geometry.special_orthogonal import SpecialOrthogonal
PI = gs.pi
PI2 = PI * PI
PI3 = PI * PI2
PI4 = PI * PI3
PI5 = PI * PI4
PI6 = PI * PI5
PI7 = PI * PI6
PI8 = PI * PI7
ATOL = 1e-5
def _squared_dist_grad_point_a(point_a, point_b, metric):
"""Compute gradient of squared_dist wrt point_a.
Compute the Riemannian gradient of the squared geodesic
distance with respect to the first point point_a.
Parameters
----------
point_a : array-like, shape=[..., dim]
Point.
point_b : array-like, shape=[..., dim]
Point.
metric : SpecialEuclideanMatrixCannonicalLeftMetric
Metric defining the distance.
Returns
-------
_ : array-like, shape=[..., dim]
Riemannian gradient, in the form of a tangent
vector at base point : point_a.
"""
return -2 * metric.log(point_b, point_a)
def _squared_dist_grad_point_b(point_a, point_b, metric):
"""Compute gradient of squared_dist wrt point_b.
Compute the Riemannian gradient of the squared geodesic
distance with respect to the second point point_b.
Parameters
----------
point_a : array-like, shape=[..., dim]
Point.
point_b : array-like, shape=[..., dim]
Point.
metric : SpecialEuclideanMatrixCannonicalLeftMetric
Metric defining the distance.
Returns
-------
_ : array-like, shape=[..., dim]
Riemannian gradient, in the form of a tangent
vector at base point : point_b.
"""
return -2 * metric.log(point_a, point_b)
@gs.autodiff.custom_gradient(_squared_dist_grad_point_a, _squared_dist_grad_point_b)
def _squared_dist(point_a, point_b, metric):
"""Compute geodesic distance between two points.
Compute the squared geodesic distance between point_a
and point_b, as defined by the metric.
This is an auxiliary private function that:
- is called by the method `squared_dist` of the class
SpecialEuclideanMatrixCannonicalLeftMetric,
- has been created to support the implementation
of custom_gradient in tensorflow backend.
Parameters
----------
point_a : array-like, shape=[..., dim]
Point.
point_b : array-like, shape=[..., dim]
Point.
metric : SpecialEuclideanMatrixCannonicalLeftMetric
Metric defining the distance.
Returns
-------
_ : array-like, shape=[...,]
Geodesic distance between point_a and point_b.
"""
return metric.private_squared_dist(point_a, point_b)
def homogeneous_representation(rotation, translation, output_shape, constant=1.0):
r"""Embed rotation, translation couples into n+1 square matrices.
Construct a block matrix of size :math: `n + 1 \times n + 1` of the form
.. math::
\matvec{cc}{R & t\\
0&c}
where :math: `R` is a square matrix, :math: `t` a vector of size
:math: `n`, and :math: `c` a constant (either 0 or 1 should be used).
Parameters
----------
rotation : array-like, shape=[..., n, n]
Square Matrix.
translation : array-like, shape=[..., n]
Vector.
output_shape : tuple of int
Desired output shape. This is need for vectorization.
constant : float or array-like of shape [...]
Constant to use at the last line and column of the square matrix.
Optional, default: 1.
Returns
-------
mat: array-like, shape=[..., n + 1, n + 1]
Square Matrix of size n + 1. It can represent an element of the
special euclidean group or its Lie algebra.
"""
mat = gs.concatenate((rotation, translation[..., None]), axis=-1)
last_line = gs.zeros(output_shape)[..., -1]
if isinstance(constant, float):
last_col = constant * gs.ones_like(translation)[..., None, -1]
else:
last_col = constant[..., None]
last_line = gs.concatenate([last_line[..., :-1], last_col], axis=-1)
mat = gs.concatenate((mat, last_line[..., None, :]), axis=-2)
return mat
def submersion(point):
"""Define SE(n) as the pre-image of identity.
Parameters
----------
point : array-like, shape=[..., n + 1, n + 1]
Point.
Returns
-------
submersed_point : array-like, shape=[..., n + 1, n + 1]
Submersed Point.
"""
n = point.shape[-1] - 1
rot = point[..., :n, :n]
vec = point[..., n, :n]
scalar = point[..., n, n]
submersed_rot = Matrices.mul(rot, Matrices.transpose(rot))
return homogeneous_representation(submersed_rot, vec, point.shape, constant=scalar)
def tangent_submersion(vector, point):
"""Define the tangent space of SE(n) as the kernel of this method.
Parameters
----------
vector : array-like, shape=[..., n + 1, n + 1]
Point.
point : array-like, shape=[..., n + 1, n + 1]
Point.
Returns
-------
submersed_vector : array-like, shape=[..., n + 1, n + 1]
Submersed Vector.
"""
n = point.shape[-1] - 1
rot = point[..., :n, :n]
skew = vector[..., :n, :n]
vec = vector[..., n, :n]
scalar = vector[..., n, n]
submersed_rot = Matrices.mul(Matrices.transpose(skew), rot)
submersed_rot = Matrices.to_symmetric(submersed_rot)
return homogeneous_representation(submersed_rot, vec, point.shape, constant=scalar)
class _SpecialEuclideanMatrices(MatrixLieGroup, LevelSet):
"""Class for special Euclidean group.
Parameters
----------
n : int
Integer dimension of the underlying Euclidean space. Matrices will
be of size: (n+1) x (n+1).
Attributes
----------
rotations : SpecialOrthogonal
Subgroup of rotations of size n.
translations : Euclidean
Subgroup of translations of size n.
left_canonical_metric : InvariantMetric
The left invariant metric that corresponds to the Frobenius inner
product at the identity.
right_canonical_metric : InvariantMetric
The right invariant metric that corresponds to the Frobenius inner
product at the identity.
metric : MatricesMetric
The Euclidean (Frobenius) inner product.
"""
def __init__(self, n):
super().__init__(
n=n + 1,
dim=int((n * (n + 1)) / 2),
embedding_space=GeneralLinear(n + 1, positive_det=True),
submersion=submersion,
value=gs.eye(n + 1),
tangent_submersion=tangent_submersion,
lie_algebra=SpecialEuclideanMatrixLieAlgebra(n=n),
)
self.rotations = SpecialOrthogonal(n=n)
self.translations = Euclidean(dim=n)
self.n = n
self.left_canonical_metric = SpecialEuclideanMatrixCannonicalLeftMetric(
group=self
)
self.metric = self.left_canonical_metric
@property
def identity(self):
"""Return the identity matrix."""
return gs.eye(self.n + 1, self.n + 1)
def random_point(self, n_samples=1, bound=1.0):
"""Sample in SE(n) from the uniform distribution.
Parameters
----------
n_samples : int
Number of samples.
Optional, default: 1.
bound: float
Bound of the interval in which to sample each entry of the
translation part.
Optional, default: 1.
Returns
-------
samples : array-like, shape=[..., n + 1, n + 1]
Sample in SE(n).
"""
random_translation = self.translations.random_point(n_samples)
random_rotation = self.rotations.random_uniform(n_samples)
output_shape = (
(n_samples, self.n + 1, self.n + 1) if n_samples != 1 else (self.n + 1,) * 2
)
random_point = homogeneous_representation(
random_rotation, random_translation, output_shape
)
return random_point
@classmethod
def inverse(cls, point):
"""Return the inverse of a point.
Parameters
----------
point : array-like, shape=[..., n + 1, n + 1]
Point to be inverted.
Returns
-------
inverse : array-like, shape=[..., n + 1, n + 1]
Inverse of point.
"""
n = point.shape[-1] - 1
transposed_rot = Matrices.transpose(point[..., :n, :n])
translation = point[..., :n, -1]
translation = gs.einsum("...ij,...j->...i", transposed_rot, translation)
return homogeneous_representation(transposed_rot, -translation, point.shape)
def projection(self, mat):
"""Project a matrix on SE(n).
The upper-left n x n block is projected to SO(n) by minimizing the
Frobenius norm. The last columns is kept unchanged and used as the
translation part. The last row is discarded.
Parameters
----------
mat : array-like, shape=[..., n + 1, n + 1]
Matrix.
Returns
-------
projected : array-like, shape=[..., n + 1, n + 1]
Rotation-translation matrix in homogeneous representation.
"""
n = mat.shape[-1] - 1
projected_rot = self.rotations.projection(mat[..., :n, :n])
translation = mat[..., :n, -1]
return homogeneous_representation(projected_rot, translation, mat.shape)
class _SpecialEuclideanVectors(LieGroup):
"""Base Class for the special Euclidean groups in 2d and 3d in vector form.
i.e. the Lie group of rigid transformations. Elements of SE(2), SE(3) can
either be represented as vectors (in 2d or 3d) or as matrices in general.
The matrix representation corresponds to homogeneous coordinates. This
class is specific to the vector representation of rotations. For the matrix
representation use the SpecialEuclidean class and set `n=2` or `n=3`.
Parameter
---------
epsilon : float
Precision to use for calculations involving potential
division by 0 in rotations.
Optional, default: 0.
"""
def __init__(self, n, epsilon=0.0):
dim = n * (n + 1) // 2
LieGroup.__init__(self, dim=dim, default_point_type="vector")
self.n = n
self.epsilon = epsilon
self.rotations = SpecialOrthogonal(n=n, point_type="vector", epsilon=epsilon)
self.translations = Euclidean(dim=n)
def get_identity(self, point_type=None):
"""Get the identity of the group.
Parameters
----------
point_type : str, {'vector', 'matrix'}
The point_type of the returned value.
Optional, default: self.default_point_type
Returns
-------
identity : array-like, shape={[dim], [n + 1, n + 1]}
"""
if point_type is None:
point_type = self.default_point_type
identity = gs.zeros(self.dim)
return identity
identity = property(get_identity)
def get_point_type_shape(self, point_type=None):
"""Get the shape of the instance given the default_point_style."""
return self.get_identity(point_type).shape
def belongs(self, point):
"""Evaluate if a point belongs to SE(2) or SE(3).
Parameters
----------
point : array-like, shape=[..., dimension]
Point to check.
Returns
-------
belongs : array-like, shape=[...,]
Boolean indicating whether point belongs to SE(2) or SE(3).
"""
point_dim = point.shape[-1]
point_ndim = point.ndim
belongs = gs.logical_and(point_dim == self.dim, point_ndim < 3)
belongs = gs.logical_and(
belongs, self.rotations.belongs(point[..., : self.rotations.dim])
)
return belongs
def regularize(self, point):
"""Regularize a point to the default representation for SE(n).
Parameters
----------
point : array-like, shape=[..., 3]
Point to regularize.
Returns
-------
point : array-like, shape=[..., 3]
Regularized point.
"""
rotations = self.rotations
dim_rotations = rotations.dim
regularized_point = point
rot_vec = regularized_point[..., :dim_rotations]
regularized_rot_vec = rotations.regularize(rot_vec)
translation = regularized_point[..., dim_rotations:]
return gs.concatenate([regularized_rot_vec, translation], axis=-1)
@geomstats.vectorization.decorator(["else", "vector", "else"])
def regularize_tangent_vec_at_identity(self, tangent_vec, metric=None):
"""Regularize a tangent vector at the identity.
Parameters
----------
tangent_vec: array-like, shape=[..., 3]
Tangent vector at base point.
metric : RiemannianMetric
Metric.
Optional, default: None.
Returns
-------
regularized_vec : array-like, shape=[..., 3]
Regularized vector.
"""
return self.regularize_tangent_vec(tangent_vec, self.identity, metric)
@geomstats.vectorization.decorator(["else", "vector"])
def matrix_from_vector(self, vec):
"""Convert point in vector point-type to matrix.
Parameters
----------
vec : array-like, shape=[..., dimension]
Vector.
Returns
-------
mat : array-like, shape=[..., n+1, n+1]
Matrix.
"""
vec = self.regularize(vec)
output_shape = (
(vec.shape[0], self.n + 1, self.n + 1)
if vec.ndim == 2
else (self.n + 1,) * 2
)
rot_vec = vec[..., : self.rotations.dim]
trans_vec = vec[..., self.rotations.dim :]
rot_mat = self.rotations.matrix_from_rotation_vector(rot_vec)
return homogeneous_representation(rot_mat, trans_vec, output_shape)
@geomstats.vectorization.decorator(["else", "vector", "vector"])
def compose(self, point_a, point_b):
r"""Compose two elements of SE(2) or SE(3).
Parameters
----------
point_a : array-like, shape=[..., dimension]
Point of the group.
point_b : array-like, shape=[..., dimension]
Point of the group.
Equation
--------
(:math: `(R_1, t_1) \\cdot (R_2, t_2) = (R_1 R_2, R_1 t_2 + t_1)`)
Returns
-------
composition : array-like, shape=[..., dimension]
Composition of point_a and point_b.
"""
rotations = self.rotations
dim_rotations = rotations.dim
point_a = self.regularize(point_a)
point_b = self.regularize(point_b)
rot_vec_a = point_a[..., :dim_rotations]
rot_mat_a = rotations.matrix_from_rotation_vector(rot_vec_a)
rot_vec_b = point_b[..., :dim_rotations]
rot_mat_b = rotations.matrix_from_rotation_vector(rot_vec_b)
translation_a = point_a[..., dim_rotations:]
translation_b = point_b[..., dim_rotations:]
composition_rot_mat = gs.matmul(rot_mat_a, rot_mat_b)
composition_rot_vec = rotations.rotation_vector_from_matrix(composition_rot_mat)
composition_translation = (
gs.einsum("...j,...kj->...k", translation_b, rot_mat_a) + translation_a
)
composition = gs.concatenate(
(composition_rot_vec, composition_translation), axis=-1
)
return self.regularize(composition)
@geomstats.vectorization.decorator(["else", "vector"])
def inverse(self, point):
r"""Compute the group inverse in SE(n).
Parameters
----------
point: array-like, shape=[..., dimension]
Point.
Returns
-------
inverse_point : array-like, shape=[..., dimension]
Inverted point.
Notes
-----
:math:`(R, t)^{-1} = (R^{-1}, R^{-1}.(-t))`
"""
rotations = self.rotations
dim_rotations = rotations.dim
point = self.regularize(point)
rot_vec = point[:, :dim_rotations]
translation = point[:, dim_rotations:]
inverse_rotation = -rot_vec
inv_rot_mat = rotations.matrix_from_rotation_vector(inverse_rotation)
inverse_translation = gs.einsum(
"ni,nij->nj", -translation, gs.transpose(inv_rot_mat, axes=(0, 2, 1))
)
inverse_point = gs.concatenate([inverse_rotation, inverse_translation], axis=-1)
return self.regularize(inverse_point)
@geomstats.vectorization.decorator(["else", "vector"])
def exp_from_identity(self, tangent_vec):
"""Compute group exponential of the tangent vector at the identity.
Parameters
----------
tangent_vec: array-like, shape=[..., 3]
Tangent vector at base point.
Returns
-------
group_exp: array-like, shape=[..., 3]
Group exponential of the tangent vectors computed
at the identity.
"""
rotations = self.rotations
dim_rotations = rotations.dim
rot_vec = tangent_vec[..., :dim_rotations]
rot_vec_regul = self.rotations.regularize(rot_vec)
rot_vec_regul = gs.to_ndarray(rot_vec_regul, to_ndim=2, axis=1)
transform = self._exp_translation_transform(rot_vec_regul)
translation = tangent_vec[..., dim_rotations:]
exp_translation = gs.einsum("ijk, ik -> ij", transform, translation)
group_exp = gs.concatenate([rot_vec, exp_translation], axis=1)
group_exp = self.regularize(group_exp)
return group_exp
@geomstats.vectorization.decorator(["else", "vector"])
def log_from_identity(self, point):
"""Compute the group logarithm of the point at the identity.
Parameters
----------
point: array-like, shape=[..., 3]
Point.
Returns
-------
group_log: array-like, shape=[..., 3]
Group logarithm in the Lie algebra.
"""
point = self.regularize(point)
rotations = self.rotations
dim_rotations = rotations.dim
rot_vec = point[:, :dim_rotations]
translation = point[:, dim_rotations:]
transform = self._log_translation_transform(rot_vec)
log_translation = gs.einsum("ijk, ik -> ij", transform, translation)
return gs.concatenate([rot_vec, log_translation], axis=1)
def random_point(self, n_samples=1, bound=1.0, **kwargs):
r"""Sample in SE(n) with the uniform distribution.
Parameters
----------
n_samples : int
Number of samples.
Optional, default: 1.
bound : float
Upper bound for the translation part of the sample.
Optional, default: 1.
Returns
-------
random_point : array-like, shape=[..., dimension]
Sample.
"""
random_translation = self.translations.random_point(n_samples, bound)
random_rot_vec = self.rotations.random_uniform(n_samples)
return gs.concatenate([random_rot_vec, random_translation], axis=-1)
class _SpecialEuclidean2Vectors(_SpecialEuclideanVectors):
"""Class for the special Euclidean group in 2d, SE(2).
i.e. the Lie group of rigid transformations. Elements of SE(32 can either
be represented as vectors (in 2d) or as matrices in general. The matrix
representation corresponds to homogeneous coordinates. This class is
specific to the vector representation of rotations. For the matrix
representation use the SpecialEuclidean class and set `n=2`.
Parameter
---------
epsilon : float
Precision to use for calculations involving potential
division by 0 in rotations.
Optional, default: 0.
"""
def __init__(self, epsilon=0.0):
super(_SpecialEuclidean2Vectors, self).__init__(n=2, epsilon=epsilon)
def regularize_tangent_vec(self, tangent_vec, base_point, metric=None):
"""Regularize a tangent vector at a base point.
Parameters
----------
tangent_vec: array-like, shape=[..., 3]
Tangent vector at base point.
base_point : array-like, shape=[..., 3]
Base point.
metric : RiemannianMetric
Metric.
Optional, defaults to self.left_canonical_metric if None.
Returns
-------
regularized_vec : array-like, shape=[..., 3]
Regularized vector.
"""
if metric is None:
metric = self.left_canonical_metric
rotations = self.rotations
dim_rotations = rotations.dim
rot_tangent_vec = tangent_vec[..., :dim_rotations]
rot_base_point = base_point[..., :dim_rotations]
rotations_vec = rotations.regularize_tangent_vec(
tangent_vec=rot_tangent_vec, base_point=rot_base_point
)
return gs.concatenate(
[rotations_vec, tangent_vec[..., dim_rotations:]], axis=-1
)
@geomstats.vectorization.decorator(["else", "vector", "else"])
def jacobian_translation(self, point, left_or_right="left"):
"""Compute the Jacobian matrix resulting from translation.
Compute the matrix of the differential of the left/right translations
from the identity to point in SE(3).
Parameters
----------
point: array-like, shape=[..., 3]
Point.
left_or_right: str, {'left', 'right'}
Whether to compute the jacobian of the left or right translation.
Optional, default: 'left'.
Returns
-------
jacobian : array-like, shape=[..., 3]
Jacobian of the left / right translation.
"""
if left_or_right not in ("left", "right"):
raise ValueError("`left_or_right` must be `left` or `right`.")
point = self.regularize(point)
n_points, _ = point.shape
return gs.array([gs.eye(self.dim)] * n_points)
def _exp_translation_transform(self, rot_vec):
base_1 = gs.eye(2)
base_2 = self.rotations.skew_matrix_from_vector(gs.ones(1))
cos_coef = rot_vec * utils.taylor_exp_even_func(
rot_vec ** 2, utils.cosc_close_0, order=3
)
sin_coef = utils.taylor_exp_even_func(rot_vec ** 2, utils.sinc_close_0, order=3)
sin_term = gs.einsum("...i,...jk->...jk", sin_coef, base_1)
cos_term = gs.einsum("...i,...jk->...jk", cos_coef, base_2)
transform = sin_term + cos_term
return transform
def _log_translation_transform(self, rot_vec):
exp_transform = self._exp_translation_transform(rot_vec)
inv_determinant = 0.5 / utils.taylor_exp_even_func(
rot_vec ** 2, utils.cosc_close_0, order=4
)
transform = gs.einsum(
"...l, ...jk -> ...jk", inv_determinant, Matrices.transpose(exp_transform)
)
return transform
class _SpecialEuclidean3Vectors(_SpecialEuclideanVectors):
"""Class for the special Euclidean group in 3d, SE(3).
i.e. the Lie group of rigid transformations. Elements of SE(3) can either
be represented as vectors (in 3d) or, in general, as matrices. The matrix
representation corresponds to homogeneous coordinates. This class is
specific to the vector representation of rotations. For the matrix
representation use the SpecialEuclidean class and set `n=3`.
Parameter
---------
epsilon : float
Precision to use for calculations involving potential
division by 0 in rotations.
Optional, default: 0.
"""
def __init__(self, epsilon=0.0):
super(_SpecialEuclidean3Vectors, self).__init__(n=3, epsilon=epsilon)
def regularize_tangent_vec(self, tangent_vec, base_point, metric=None):
"""Regularize a tangent vector at a base point.
Parameters
----------
tangent_vec: array-like, shape=[..., 3]
Tangent vector at base point.
base_point : array-like, shape=[..., 3]
Base point.
metric : RiemannianMetric
Metric.
Optional, defaults to self.left_canonical_metric if None.
Returns
-------
regularized_vec : array-like, shape=[..., 3]
Regularized vector.
"""
if metric is None:
metric = self.left_canonical_metric
rotations = self.rotations
dim_rotations = rotations.dim
rot_tangent_vec = tangent_vec[..., :dim_rotations]
rot_base_point = base_point[..., :dim_rotations]
metric_mat = metric.metric_mat_at_identity
rot_metric_mat = metric_mat[:dim_rotations, :dim_rotations]
rot_metric = InvariantMetric(
group=rotations,
metric_mat_at_identity=rot_metric_mat,
left_or_right=metric.left_or_right,
)
rotations_vec = rotations.regularize_tangent_vec(
tangent_vec=rot_tangent_vec, base_point=rot_base_point, metric=rot_metric
)
return gs.concatenate(
[rotations_vec, tangent_vec[..., dim_rotations:]], axis=-1
)
@geomstats.vectorization.decorator(["else", "vector", "else"])
def jacobian_translation(self, point, left_or_right="left"):
"""Compute the Jacobian matrix resulting from translation.
Compute the matrix of the differential of the left/right translations
from the identity to point in SE(3).
Parameters
----------
point: array-like, shape=[..., 3]
Point.
left_or_right: str, {'left', 'right'}
Whether to compute the jacobian of the left or right translation.
Optional, default: 'left'.
Returns
-------
jacobian : array-like, shape=[..., 3]
Jacobian of the left / right translation.
"""
if left_or_right not in ("left", "right"):
raise ValueError("`left_or_right` must be `left` or `right`.")
rotations = self.rotations
translations = self.translations
dim_rotations = rotations.dim
dim_translations = translations.dim
point = self.regularize(point)
n_points, _ = point.shape
rot_vec = point[:, :dim_rotations]
jacobian_rot = self.rotations.jacobian_translation(
point=rot_vec, left_or_right=left_or_right
)
jacobian_rot = gs.to_ndarray(jacobian_rot, to_ndim=3)
block_zeros_1 = gs.zeros((n_points, dim_rotations, dim_translations))
jacobian_block_line_1 = gs.concatenate([jacobian_rot, block_zeros_1], axis=2)
if left_or_right == "left":
rot_mat = self.rotations.matrix_from_rotation_vector(rot_vec)
jacobian_trans = rot_mat
block_zeros_2 = gs.zeros((n_points, dim_translations, dim_rotations))
jacobian_block_line_2 = gs.concatenate(
[block_zeros_2, jacobian_trans], axis=2
)
else:
inv_skew_mat = -self.rotations.skew_matrix_from_vector(rot_vec)
eye = gs.to_ndarray(gs.eye(self.n), to_ndim=3)
eye = gs.tile(eye, [n_points, 1, 1])
jacobian_block_line_2 = gs.concatenate([inv_skew_mat, eye], axis=2)
jacobian = gs.concatenate(
[jacobian_block_line_1, jacobian_block_line_2], axis=-2
)
return jacobian[0] if 1 in (len(point), point.ndim) else jacobian
def _exponential_matrix(self, rot_vec):
"""Compute exponential of rotation matrix represented by rot_vec.
Parameters
----------
rot_vec : array-like, shape=[..., 3]
Returns
-------
exponential_mat : Matrix exponential of rot_vec
"""
# TODO (nguigs): find usecase for this method
rot_vec = self.rotations.regularize(rot_vec)
n_rot_vecs = 1 if rot_vec.ndim == 1 else len(rot_vec)
angle = gs.linalg.norm(rot_vec, axis=-1)
angle = gs.to_ndarray(angle, to_ndim=2, axis=1)
skew_rot_vec = self.rotations.skew_matrix_from_vector(rot_vec)
coef_1 = gs.empty_like(angle)
coef_2 = gs.empty_like(coef_1)
mask_0 = gs.equal(angle, 0)
mask_0 = gs.squeeze(mask_0, axis=1)
mask_close_to_0 = gs.isclose(angle, 0)
mask_close_to_0 = gs.squeeze(mask_close_to_0, axis=1)
mask_else = ~mask_0 & ~mask_close_to_0
coef_1[mask_close_to_0] = 1.0 / 2.0 - angle[mask_close_to_0] ** 2 / 24.0
coef_2[mask_close_to_0] = 1.0 / 6.0 - angle[mask_close_to_0] ** 3 / 120.0
# TODO (nina): Check if the discontinuity at 0 is expected.
coef_1[mask_0] = 0
coef_2[mask_0] = 0
coef_1[mask_else] = angle[mask_else] ** (-2) * (1.0 - gs.cos(angle[mask_else]))
coef_2[mask_else] = angle[mask_else] ** (-2) * (
1.0 - (gs.sin(angle[mask_else]) / angle[mask_else])
)
term_1 = gs.zeros((n_rot_vecs, self.n, self.n))
term_2 = gs.zeros_like(term_1)
for i in range(n_rot_vecs):
term_1[i] = gs.eye(self.n) + skew_rot_vec[i] * coef_1[i]
term_2[i] = gs.matmul(skew_rot_vec[i], skew_rot_vec[i]) * coef_2[i]
exponential_mat = term_1 + term_2
return exponential_mat
def _exp_translation_transform(self, rot_vec):
"""Compute matrix associated to rot_vec for the translation part in exp.
Parameters
----------
rot_vec : array-like, shape=[..., 3]
Returns
-------
transform : array-like, shape=[..., 3, 3]
Matrix to be applied to the translation part in exp.
"""
sq_angle = gs.sum(rot_vec ** 2, axis=-1)
skew_mat = self.rotations.skew_matrix_from_vector(rot_vec)
sq_skew_mat = gs.matmul(skew_mat, skew_mat)
coef_1_ = utils.taylor_exp_even_func(sq_angle, utils.cosc_close_0, order=4)
coef_2_ = utils.taylor_exp_even_func(sq_angle, utils.var_sinc_close_0, order=4)
term_1 = gs.einsum("...,...ij->...ij", coef_1_, skew_mat)
term_2 = gs.einsum("...,...ij->...ij", coef_2_, sq_skew_mat)
term_id = gs.eye(3)
transform = term_id + term_1 + term_2
return transform
def _log_translation_transform(self, rot_vec):
"""Compute matrix associated to rot_vec for the translation part in log.
Parameters
----------
rot_vec : array-like, shape=[..., 3]
Returns
-------
transform : array-like, shape=[..., 3, 3]
Matrix to be applied to the translation part in log
"""
n_samples = rot_vec.shape[0]
angle = gs.linalg.norm(rot_vec, axis=1)
angle = gs.to_ndarray(angle, to_ndim=2, axis=1)
skew_mat = self.rotations.skew_matrix_from_vector(rot_vec)
sq_skew_mat = gs.matmul(skew_mat, skew_mat)
mask_close_0 = gs.isclose(angle, 0.0)
mask_close_pi = gs.isclose(angle, gs.pi)
mask_else = ~mask_close_0 & ~mask_close_pi
mask_close_0_float = gs.cast(mask_close_0, gs.float32)
mask_close_pi_float = gs.cast(mask_close_pi, gs.float32)
mask_else_float = gs.cast(mask_else, gs.float32)
mask_0 = gs.isclose(angle, 0.0, atol=1e-7)
mask_0_float = gs.cast(mask_0, gs.float32)
angle += mask_0_float * gs.ones_like(angle)
coef_1 = -0.5 * gs.ones_like(angle)
coef_2 = gs.zeros_like(angle)
coef_2 += mask_close_0_float * (
1.0 / 12.0
+ angle ** 2 / 720.0
+ angle ** 4 / 30240.0
+ angle ** 6 / 1209600.0
)
delta_angle = angle - gs.pi
coef_2 += mask_close_pi_float * (
1.0 / PI2
+ (PI2 - 8.0) * delta_angle / (4.0 * PI3)
- ((PI2 - 12.0) * delta_angle ** 2 / (4.0 * PI4))
+ ((-192.0 + 12.0 * PI2 + PI4) * delta_angle ** 3 / (48.0 * PI5))
- ((-240.0 + 12.0 * PI2 + PI4) * delta_angle ** 4 / (48.0 * PI6))
+ (
(-2880.0 + 120.0 * PI2 + 10.0 * PI4 + PI6)
* delta_angle ** 5
/ (480.0 * PI7)
)
- (
(-3360 + 120.0 * PI2 + 10.0 * PI4 + PI6)
* delta_angle ** 6
/ (480.0 * PI8)
)
)
psi = 0.5 * angle * gs.sin(angle) / (1 - gs.cos(angle))
coef_2 += mask_else_float * (1 - psi) / (angle ** 2)
term_1 = gs.einsum("...i,...ij->...ij", coef_1, skew_mat)
term_2 = gs.einsum("...i,...ij->...ij", coef_2, sq_skew_mat)
term_id = gs.array([gs.eye(3)] * n_samples)
transform = term_id + term_1 + term_2