-
Notifications
You must be signed in to change notification settings - Fork 239
/
pre_shape.py
1049 lines (895 loc) · 42 KB
/
pre_shape.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
"""Kendall Pre-Shape space."""
import logging
import geomstats.backend as gs
from geomstats.algebra_utils import flip_determinant
from geomstats.errors import check_tf_error
from geomstats.geometry.base import LevelSet
from geomstats.geometry.fiber_bundle import FiberBundle
from geomstats.geometry.hypersphere import Hypersphere
from geomstats.geometry.matrices import Matrices, MatricesMetric
from geomstats.geometry.quotient_metric import QuotientMetric
from geomstats.geometry.riemannian_metric import RiemannianMetric
from geomstats.integrator import integrate
class PreShapeSpace(LevelSet, FiberBundle):
r"""Class for the Kendall pre-shape space.
The pre-shape space is the sphere of the space of centered k-ad of
landmarks in :math:`R^m` (for the Frobenius norm). It is endowed with the
spherical Procrustes metric d(x, y):= arccos(tr(xy^t)).
Points are represented by :math:`k \times m` centred matrices as in
[Nava]_. Beware that this is not the usual convention from the literature.
Parameters
----------
k_landmarks : int
Number of landmarks
m_ambient : int
Number of coordinates of each landmark.
References
----------
..[Nava] Nava-Yazdani, E., H.-C. Hege, T. J.Sullivan, and C. von Tycowicz.
“Geodesic Analysis in Kendall’s Shape Space with Epidemiological
Applications.”
Journal of Mathematical Imaging and Vision 62, no. 4 549–59.
https://doi.org/10.1007/s10851-020-00945-w.
"""
def __init__(self, k_landmarks, m_ambient):
embedding_manifold = Matrices(k_landmarks, m_ambient)
embedding_metric = embedding_manifold.metric
super(PreShapeSpace, self).__init__(
dim=m_ambient * (k_landmarks - 1) - 1,
embedding_space=embedding_manifold,
submersion=embedding_metric.squared_norm,
value=1.0,
tangent_submersion=embedding_metric.inner_product,
ambient_metric=PreShapeMetric(k_landmarks, m_ambient),
)
self.k_landmarks = k_landmarks
self.m_ambient = m_ambient
self.ambient_metric = PreShapeMetric(k_landmarks, m_ambient)
def projection(self, point):
"""Project a point on the pre-shape space.
Parameters
----------
point : array-like, shape=[..., k_landmarks, m_ambient]
Point in Matrices space.
Returns
-------
projected_point : array-like, shape=[..., k_landmarks, m_ambient]
Point projected on the pre-shape space.
"""
centered_point = self.center(point)
frob_norm = self.ambient_metric.norm(centered_point)
projected_point = gs.einsum("...,...ij->...ij", 1.0 / frob_norm, centered_point)
return projected_point
def random_point(self, n_samples=1, bound=1.0):
"""Sample in the pre-shape space from the uniform distribution.
Parameters
----------
n_samples : int
Number of samples.
Optional, default: 1.
bound : float
Not used.
Returns
-------
samples : array-like, shape=[..., dim + 1]
Points sampled on the pre-shape space.
"""
return self.random_uniform(n_samples)
def random_uniform(self, n_samples=1):
"""Sample in the pre-shape space from the uniform distribution.
Parameters
----------
n_samples : int
Number of samples.
Optional, default: 1.
Returns
-------
samples : array-like, shape=[..., k_landmarks, m_ambient]
Points sampled on the pre-shape space.
"""
samples = Hypersphere(self.m_ambient * self.k_landmarks - 1).random_uniform(
n_samples
)
samples = gs.reshape(samples, (-1, self.k_landmarks, self.m_ambient))
if n_samples == 1:
samples = samples[0]
return self.projection(samples)
@staticmethod
def is_centered(point, atol=gs.atol):
"""Check that landmarks are centered around 0.
Parameters
----------
point : array-like, shape=[..., k_landmarks, m_ambient]
Point in Matrices space.
atol : float
Tolerance at which to evaluate mean == 0.
Optional, default: backend atol.
Returns
-------
is_centered : array-like, shape=[...,]
Boolean evaluating if point is centered.
"""
mean = gs.mean(point, axis=-2)
return gs.all(gs.isclose(mean, 0.0, atol=atol), axis=-1)
@staticmethod
def center(point):
"""Center landmarks around 0.
Parameters
----------
point : array-like, shape=[..., k_landmarks, m_ambient]
Point in Matrices space.
Returns
-------
centered : array-like, shape=[..., k_landmarks, m_ambient]
Point with centered landmarks.
"""
mean = gs.mean(point, axis=-2)
return point - mean[..., None, :]
def to_tangent(self, vector, base_point):
"""Project a vector to the tangent space.
Project a vector in the embedding matrix space
to the tangent space of the pre-shape space at a base point.
Parameters
----------
vector : array-like, shape=[..., k_landmarks, m_ambient]
Vector in Matrix space.
base_point : array-like, shape=[..., k_landmarks, m_ambient]
Point on the pre-shape space defining the tangent space,
where the vector will be projected.
Returns
-------
tangent_vec : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector in the tangent space of the pre-shape space
at the base point.
"""
if not gs.all(self.is_centered(base_point)):
raise ValueError("The base_point does not belong to the pre-shape" " space")
vector = self.center(vector)
sq_norm = Matrices.frobenius_product(base_point, base_point)
inner_prod = self.ambient_metric.inner_product(base_point, vector)
coef = inner_prod / sq_norm
tangent_vec = vector - gs.einsum("...,...ij->...ij", coef, base_point)
return tangent_vec
def vertical_projection(self, tangent_vec, base_point, return_skew=False):
r"""Project to vertical subspace.
Compute the vertical component of a tangent vector :math:`w` at a
base point :math:`x` by solving the sylvester equation:
.. math::
`Axx^T + xx^TA = wx^T - xw^T`
where A is skew-symmetric. Then Ax is the vertical projection of w.
Parameters
----------
tangent_vec : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector to the pre-shape space at `base_point`.
base_point : array-like, shape=[..., k_landmarks, m_ambient]
Point on the pre-shape space.
return_skew : bool
Whether to return the skew-symmetric matrix A.
Optional, default: False
Returns
-------
vertical : array-like, shape=[..., k_landmarks, m_ambient]
Vertical component of `tangent_vec`.
skew : array-like, shape=[..., m_ambient, m_ambient]
Vertical component of `tangent_vec`.
"""
transposed_point = Matrices.transpose(base_point)
left_term = gs.matmul(transposed_point, base_point)
alignment = gs.matmul(Matrices.transpose(tangent_vec), base_point)
right_term = alignment - Matrices.transpose(alignment)
skew = gs.linalg.solve_sylvester(left_term, left_term, right_term)
vertical = -gs.matmul(base_point, skew)
return (vertical, skew) if return_skew else vertical
def is_horizontal(self, tangent_vec, base_point, atol=gs.atol):
"""Check whether the tangent vector is horizontal at base_point.
Parameters
----------
tangent_vec : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector.
base_point : array-like, shape=[..., k_landmarks, m_ambient]
Point on the manifold.
Optional, default: none.
atol : float
Absolute tolerance.
Optional, default: backend atol.
Returns
-------
is_tangent : bool
Boolean denoting if tangent vector is horizontal.
"""
product = gs.matmul(Matrices.transpose(tangent_vec), base_point)
is_tangent = self.is_tangent(tangent_vec, base_point, atol)
is_symmetric = Matrices.is_symmetric(product, atol)
return gs.logical_and(is_tangent, is_symmetric)
def align(self, point, base_point, **kwargs):
"""Align point to base_point.
Find the optimal rotation R in SO(m) such that the base point and
R.point are well positioned.
Parameters
----------
point : array-like, shape=[..., k_landmarks, m_ambient]
Point on the manifold.
base_point : array-like, shape=[..., k_landmarks, m_ambient]
Point on the manifold.
Returns
-------
aligned : array-like, shape=[..., k_landmarks, m_ambient]
R.point.
"""
mat = gs.matmul(Matrices.transpose(point), base_point)
left, singular_values, right = gs.linalg.svd(mat)
det = gs.linalg.det(mat)
conditioning = (
singular_values[..., -2] + gs.sign(det) * singular_values[..., -1]
) / singular_values[..., 0]
if gs.any(conditioning < gs.atol):
logging.warning(
f"Singularity close, ill-conditioned matrix "
f"encountered: "
f"{conditioning[conditioning < 1e-10]}"
)
if gs.any(gs.isclose(conditioning, 0.0)):
logging.warning("Alignment matrix is not unique.")
flipped = flip_determinant(Matrices.transpose(right), det)
return Matrices.mul(point, left, Matrices.transpose(flipped))
def integrability_tensor_old(self, tangent_vec_a, tangent_vec_b, base_point):
r"""Compute the fundamental tensor A of the submersion (old).
The fundamental tensor A is defined for tangent vectors of the total
space by [O'Neill]_ :math:`A_X Y = ver\nabla^M_{hor X} (hor Y)
+ hor \nabla^M_{hor X}( ver Y)` where :math:`hor,ver` are the
horizontal and vertical projections.
For the pre-shape space, we have closed-form expressions and the result
does not depend on the vertical part of :math:`X`.
Parameters
----------
tangent_vec_a : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
tangent_vec_b : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
base_point : array-like, shape=[..., k_landmarks, m_ambient]
Point of the total space.
Returns
-------
vector : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`, result of the A tensor applied to
`tangent_vec_a` and `tangent_vec_b`.
References
----------
.. [O'Neill] O’Neill, Barrett. The Fundamental Equations of a
Submersion, Michigan Mathematical Journal 13, no. 4 (December 1966):
459–69. https://doi.org/10.1307/mmj/1028999604.
"""
# Only the horizontal part of a counts
horizontal_a = self.horizontal_projection(tangent_vec_a, base_point)
vertical_b, skew = self.vertical_projection(
tangent_vec_b, base_point, return_skew=True
)
horizontal_b = tangent_vec_b - vertical_b
# For the horizontal part of b
transposed_point = Matrices.transpose(base_point)
sigma = gs.matmul(transposed_point, base_point)
alignment = gs.matmul(Matrices.transpose(horizontal_a), horizontal_b)
right_term = alignment - Matrices.transpose(alignment)
skew_hor = gs.linalg.solve_sylvester(sigma, sigma, right_term)
vertical = -gs.matmul(base_point, skew_hor)
# For the vertical part of b
vert_part = -gs.matmul(horizontal_a, skew)
tangent_vert = self.to_tangent(vert_part, base_point)
horizontal_ = self.horizontal_projection(tangent_vert, base_point)
return vertical + horizontal_
def integrability_tensor(self, tangent_vec_x, tangent_vec_e, base_point):
r"""Compute the fundamental tensor A of the submersion.
The fundamental tensor A is defined for tangent vectors of the total
space by [O'Neill]_ :math:`A_X Y = ver\nabla^M_{hor X} (hor Y)
+ hor \nabla^M_{hor X}( ver Y)`
where :math:`hor, ver` are the horizontal and vertical projections.
For the Kendall shape space, we have the closed-form expression at
base-point P [Pennec]_:
:math:`A_X E = P Sylv_P(E^\top hor(X)) + F + <F,P> P` where
:math:`F = hor(X) Sylv_P(P^\top E)` and :math:`Sylv_P(B)` is the
unique skew-symmetric matrix :math:`\Omega` solution of
:math:`P^\top P \Omega + \Omega P^\top P = B - B^\top`.
Parameters
----------
tangent_vec_x : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
tangent_vec_e : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
base_point : array-like, shape=[..., k_landmarks, m_ambient]
Point of the total space.
Returns
-------
vector : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`, result of the A tensor applied to
`tangent_vec_x` and `tangent_vec_e`.
References
----------
.. [O'Neill] O’Neill, Barrett. The Fundamental Equations of a
Submersion, Michigan Mathematical Journal 13, no. 4 (December 1966):
459–69. https://doi.org/10.1307/mmj/1028999604.
.. [Pennec] Pennec, Xavier. Computing the curvature and its gradient
in Kendall shape spaces. Unpublished.
"""
hor_x = self.horizontal_projection(tangent_vec_x, base_point)
p_top = Matrices.transpose(base_point)
p_top_p = gs.matmul(p_top, base_point)
def sylv_p(mat_b):
"""Solves Sylvester equation for vertical component."""
return gs.linalg.solve_sylvester(
p_top_p, p_top_p, mat_b - Matrices.transpose(mat_b)
)
e_top_hor_x = gs.matmul(Matrices.transpose(tangent_vec_e), hor_x)
sylv_e_top_hor_x = sylv_p(e_top_hor_x)
p_top_e = gs.matmul(p_top, tangent_vec_e)
sylv_p_top_e = sylv_p(p_top_e)
result = gs.matmul(base_point, sylv_e_top_hor_x) + gs.matmul(
hor_x, sylv_p_top_e
)
return result
def integrability_tensor_derivative(
self,
horizontal_vec_x,
horizontal_vec_y,
nabla_x_y,
tangent_vec_e,
nabla_x_e,
base_point,
):
r"""Compute the covariant derivative of the integrability tensor A.
The horizontal covariant derivative :math:`\nabla_X (A_Y E)` is
necessary to compute the covariant derivative of the curvature in a
submersion.
The components :math:`\nabla_X (A_Y E)` and :math:`A_Y E` are
computed here for the Kendall shape space at base-point
:math:`P = base_point` for horizontal vector fields fields :math:
`X, Y` extending the values :math:`X|_P = horizontal_vec_x`,
:math:`Y|_P = horizontal_vec_y` and a general vector field
:math:`E` extending :math:`E|_P = tangent_vec_e` in a neighborhood
of the base-point P with covariant derivatives
:math:`\nabla_X Y |_P = nabla_x_y` and
:math:`\nabla_X E |_P = nabla_x_e`.
Parameters
----------
horizontal_vec_x : array-like, shape=[..., k_landmarks, m_ambient]
Horizontal tangent vector at `base_point`.
horizontal_vec_y : array-like, shape=[..., k_landmarks, m_ambient]
Horizontal tangent vector at `base_point`.
nabla_x_y : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
tangent_vec_e : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
nabla_x_e : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
base_point : array-like, shape=[..., k_landmarks, m_ambient]
Point of the total space.
Returns
-------
nabla_x_a_y_e : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`, result of :math:`\nabla_X^S
(A_Y E)`.
a_y_e : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`, result of :math:`A_Y E`.
References
----------
.. [Pennec] Pennec, Xavier. Computing the curvature and its gradient
in Kendall shape spaces. Unpublished.
"""
if not gs.all(self.belongs(base_point)):
raise ValueError("The base_point does not belong to the pre-shape" " space")
if not gs.all(self.is_horizontal(horizontal_vec_x, base_point)):
raise ValueError("Tangent vector x is not horizontal")
if not gs.all(self.is_horizontal(horizontal_vec_y, base_point)):
raise ValueError("Tangent vector y is not horizontal")
if not gs.all(self.is_tangent(nabla_x_y, base_point)):
raise ValueError("Vector nabla_x_y is not tangent")
a_x_y = self.integrability_tensor(
horizontal_vec_x, horizontal_vec_y, base_point
)
if not gs.all(self.is_horizontal(nabla_x_y - a_x_y, base_point)):
raise ValueError(
"Tangent vector nabla_x_y is not the gradient "
"of a horizontal distrinbution"
)
if not gs.all(self.is_tangent(tangent_vec_e, base_point)):
raise ValueError("Tangent vector e is not tangent")
if not gs.all(self.is_tangent(nabla_x_e, base_point)):
raise ValueError("Vector nabla_x_e is not tangent")
p_top = Matrices.transpose(base_point)
p_top_p = gs.matmul(p_top, base_point)
e_top = Matrices.transpose(tangent_vec_e)
x_top = Matrices.transpose(horizontal_vec_x)
y_top = Matrices.transpose(horizontal_vec_y)
def sylv_p(mat_b):
"""Solves Sylvester equation for vertical component."""
return gs.linalg.solve_sylvester(
p_top_p, p_top_p, mat_b - Matrices.transpose(mat_b)
)
omega_ep = sylv_p(gs.matmul(p_top, tangent_vec_e))
omega_ye = sylv_p(gs.matmul(e_top, horizontal_vec_y))
tangent_vec_b = gs.matmul(horizontal_vec_x, omega_ye)
tangent_vec_e_sym = tangent_vec_e - 2.0 * gs.matmul(base_point, omega_ep)
a_y_e = gs.matmul(base_point, omega_ye) + gs.matmul(horizontal_vec_y, omega_ep)
tmp_tangent_vec_p = (
gs.matmul(e_top, nabla_x_y)
- gs.matmul(y_top, nabla_x_e)
- 2.0 * gs.matmul(p_top, tangent_vec_b)
)
tmp_tangent_vec_y = gs.matmul(p_top, nabla_x_e) + gs.matmul(
x_top, tangent_vec_e_sym
)
scal_x_a_y_e = self.ambient_metric.inner_product(
horizontal_vec_x, a_y_e, base_point
)
nabla_x_a_y_e = (
gs.matmul(base_point, sylv_p(tmp_tangent_vec_p))
+ gs.matmul(horizontal_vec_y, sylv_p(tmp_tangent_vec_y))
+ gs.matmul(nabla_x_y, omega_ep)
+ tangent_vec_b
+ gs.einsum("...,...ij->...ij", scal_x_a_y_e, base_point)
)
return nabla_x_a_y_e, a_y_e
def integrability_tensor_derivative_parallel(
self, horizontal_vec_x, horizontal_vec_y, horizontal_vec_z, base_point
):
r"""Compute derivative of the integrability tensor A (special case).
The horizontal covariant derivative :math:`\nabla_X (A_Y Z)` of the
integrability tensor A may be computed more efficiently in the case of
parallel vector fields in the quotient space. :math:
`\nabla_X (A_Y Z)` and :math:`A_Y Z` are computed here for the
Kendall shape space with quotient-parallel vector fields :math:`X,
Y, Z` extending the values horizontal_vec_x, horizontal_vec_y and
horizontal_vec_z by parallel transport in a neighborhood of the
base-space. Such vector fields verify :math:`\nabla_X^X = A_X X =
0`, :math:`\nabla_X^Y = A_X Y` and similarly for Z.
Parameters
----------
horizontal_vec_x : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
horizontal_vec_y : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
horizontal_vec_z : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
base_point : array-like, shape=[..., k_landmarks, m_ambient]
Point of the total space.
Returns
-------
nabla_x_a_y_z : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`, result of
:math:`\nabla_X (A_Y Z)` with `X = horizontal_vec_x`,
`Y = horizontal_vec_y` and `Z = horizontal_vec_z`.
a_y_z : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`, result of :math:`A_Y Z`
with `Y = horizontal_vec_y` and `Z = horizontal_vec_z`.
References
----------
.. [Pennec] Pennec, Xavier. Computing the curvature and its gradient
in Kendall shape spaces. Unpublished.
"""
# Vectors X and Y have to be horizontal.
if not gs.all(self.is_centered(base_point)):
raise ValueError("The base_point does not belong to the pre-shape" " space")
if not gs.all(self.is_horizontal(horizontal_vec_x, base_point)):
raise ValueError("Tangent vector x is not horizontal")
if not gs.all(self.is_horizontal(horizontal_vec_y, base_point)):
raise ValueError("Tangent vector y is not horizontal")
if not gs.all(self.is_horizontal(horizontal_vec_z, base_point)):
raise ValueError("Tangent vector z is not horizontal")
p_top = Matrices.transpose(base_point)
p_top_p = gs.matmul(p_top, base_point)
def sylv_p(mat_b):
"""Solves Sylvester equation for vertical component."""
return gs.linalg.solve_sylvester(
p_top_p, p_top_p, mat_b - Matrices.transpose(mat_b)
)
z_top = Matrices.transpose(horizontal_vec_z)
y_top = Matrices.transpose(horizontal_vec_y)
omega_yz = sylv_p(gs.matmul(z_top, horizontal_vec_y))
a_y_z = gs.matmul(base_point, omega_yz)
omega_xy = sylv_p(gs.matmul(y_top, horizontal_vec_x))
omega_xz = sylv_p(gs.matmul(z_top, horizontal_vec_x))
omega_yz_x = gs.matmul(horizontal_vec_x, omega_yz)
omega_xz_y = gs.matmul(horizontal_vec_y, omega_xz)
omega_xy_z = gs.matmul(horizontal_vec_z, omega_xy)
tangent_vec_f = 2.0 * omega_yz_x + omega_xz_y - omega_xy_z
omega_fp = sylv_p(gs.matmul(p_top, tangent_vec_f))
omega_fp_p = gs.matmul(base_point, omega_fp)
nabla_x_a_y_z = omega_yz_x - omega_fp_p
return nabla_x_a_y_z, a_y_z
def iterated_integrability_tensor_derivative_parallel(
self, horizontal_vec_x, horizontal_vec_y, base_point
):
r"""Compute iterated derivatives of the integrability tensor A.
The iterated horizontal covariant derivative
:math:`\nabla_X (A_Y A_X Y)` (where :math:`X` and :math:`Y` are
horizontal vector fields) is a key ingredient in the computation of
the covariant derivative of the directional curvature in a submersion.
The components :math:`\nabla_X (A_Y A_X Y)`, :math:`A_X A_Y A_X Y`,
:math:`\nabla_X (A_X Y)`, and intermediate computations
:math:`A_Y A_X Y` and :math:`A_X Y` are computed here for the
Kendall shape space in the special case of quotient-parallel vector
fields :math:`X, Y` extending the values horizontal_vec_x and
horizontal_vec_y by parallel transport in a neighborhood.
Such vector fields verify :math:`\nabla_X^X = A_X X` and :math:
`\nabla_X^Y = A_X Y`.
Parameters
----------
horizontal_vec_x : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
horizontal_vec_y : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
base_point : array-like, shape=[..., k_landmarks, m_ambient]
Point of the total space.
Returns
-------
nabla_x_a_y_a_x_y : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`, result of
:math:`\nabla_X^S (A_Y A_X Y)` with
`X = horizontal_vec_x` and `Y = horizontal_vec_y`.
a_x_a_y_a_x_y : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`, result of
:math:`A_X A_Y A_X Y` with
`X = horizontal_vec_x` and `Y = horizontal_vec_y`.
nabla_x_a_x_y : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`, result of
:math:`\nabla_X^S (A_X Y)` with
`X = horizontal_vec_x` and `Y = horizontal_vec_y`.
a_y_a_x_y : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`, result of :math:`A_Y A_X Y` with
`X = horizontal_vec_x` and `Y = horizontal_vec_y`.
a_x_y : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`, result of :math:`A_X Y` with
`X = horizontal_vec_x` and `Y = horizontal_vec_y`.
References
----------
.. [Pennec] Pennec, Xavier. Computing the curvature and its gradient
in Kendall shape spaces. Unpublished.
"""
if not gs.all(self.is_centered(base_point)):
raise ValueError("The base_point does not belong to the pre-shape" " space")
if not gs.all(self.is_horizontal(horizontal_vec_x, base_point)):
raise ValueError("Tangent vector x is not horizontal")
if not gs.all(self.is_horizontal(horizontal_vec_y, base_point)):
raise ValueError("Tangent vector y is not horizontal")
p_top = Matrices.transpose(base_point)
p_top_p = gs.matmul(p_top, base_point)
def sylv_p(mat_b):
"""Solves Sylvester equation for vertical component."""
return gs.linalg.solve_sylvester(
p_top_p, p_top_p, mat_b - Matrices.transpose(mat_b)
)
y_top = Matrices.transpose(horizontal_vec_y)
x_top = Matrices.transpose(horizontal_vec_x)
x_y_top = gs.matmul(y_top, horizontal_vec_x)
omega_xy = sylv_p(x_y_top)
vertical_vec_v = gs.matmul(base_point, omega_xy)
omega_xy_x = gs.matmul(horizontal_vec_x, omega_xy)
omega_xy_y = gs.matmul(horizontal_vec_y, omega_xy)
v_top = Matrices.transpose(vertical_vec_v)
x_v_top = gs.matmul(v_top, horizontal_vec_x)
omega_xv = sylv_p(x_v_top)
omega_xv_p = gs.matmul(base_point, omega_xv)
y_v_top = gs.matmul(v_top, horizontal_vec_y)
omega_yv = sylv_p(y_v_top)
omega_yv_p = gs.matmul(base_point, omega_yv)
nabla_x_v = 3.0 * omega_xv_p + omega_xy_x
a_y_a_x_y = omega_yv_p + omega_xy_y
tmp_mat = gs.matmul(x_top, a_y_a_x_y)
a_x_a_y_a_x_y = -gs.matmul(base_point, sylv_p(tmp_mat))
omega_xv_y = gs.matmul(horizontal_vec_y, omega_xv)
omega_yv_x = gs.matmul(horizontal_vec_x, omega_yv)
omega_xy_v = gs.matmul(vertical_vec_v, omega_xy)
norms = Matrices.frobenius_product(vertical_vec_v, vertical_vec_v)
sq_norm_v_p = gs.einsum("...,...ij->...ij", norms, base_point)
tmp_mat = gs.matmul(p_top, 3.0 * omega_xv_y + 2.0 * omega_yv_x) + gs.matmul(
y_top, omega_xy_x
)
nabla_x_a_y_v = (
3.0 * omega_xv_y
+ omega_yv_x
+ omega_xy_v
- gs.matmul(base_point, sylv_p(tmp_mat))
+ sq_norm_v_p
)
return nabla_x_a_y_v, a_x_a_y_a_x_y, nabla_x_v, a_y_a_x_y, vertical_vec_v
class PreShapeMetric(RiemannianMetric):
"""Procrustes metric on the pre-shape space.
Parameters
----------
k_landmarks : int
Number of landmarks
m_ambient : int
Number of coordinates of each landmark.
"""
def __init__(self, k_landmarks, m_ambient):
super(PreShapeMetric, self).__init__(
dim=m_ambient * (k_landmarks - 1) - 1, default_point_type="matrix"
)
self.embedding_metric = MatricesMetric(k_landmarks, m_ambient)
self.sphere_metric = Hypersphere(m_ambient * k_landmarks - 1).metric
self.k_landmarks = k_landmarks
self.m_ambient = m_ambient
def inner_product(self, tangent_vec_a, tangent_vec_b, base_point=None):
"""Compute the inner-product of two tangent vectors at a base point.
Parameters
----------
tangent_vec_a : array-like, shape=[..., k_landmarks, m_ambient]
First tangent vector at base point.
tangent_vec_b : array-like, shape=[..., k_landmarks, m_ambient]
Second tangent vector at base point.
base_point : array-like, shape=[..., dk_landmarks, m_ambient]
Point on the pre-shape space.
Returns
-------
inner_prod : array-like, shape=[...,]
Inner-product of the two tangent vectors.
"""
inner_prod = self.embedding_metric.inner_product(
tangent_vec_a, tangent_vec_b, base_point
)
return inner_prod
def exp(self, tangent_vec, base_point, **kwargs):
"""Compute the Riemannian exponential of a tangent vector.
Parameters
----------
tangent_vec : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at a base point.
base_point : array-like, shape=[..., k_landmarks, m_ambient]
Point on the pre-shape space.
Returns
-------
exp : array-like, shape=[..., k_landmarks, m_ambient]
Point on the pre-shape space equal to the Riemannian exponential
of tangent_vec at the base point.
"""
flat_bp = gs.reshape(base_point, (-1, self.sphere_metric.dim + 1))
flat_tan = gs.reshape(tangent_vec, (-1, self.sphere_metric.dim + 1))
flat_exp = self.sphere_metric.exp(flat_tan, flat_bp)
return gs.reshape(flat_exp, tangent_vec.shape)
def log(self, point, base_point, **kwargs):
"""Compute the Riemannian logarithm of a point.
Parameters
----------
point : array-like, shape=[..., k_landmarks, m_ambient]
Point on the pre-shape space.
base_point : array-like, shape=[..., k_landmarks, m_ambient]
Point on the pre-shape space.
Returns
-------
log : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at the base point equal to the Riemannian logarithm
of point at the base point.
"""
flat_bp = gs.reshape(base_point, (-1, self.sphere_metric.dim + 1))
flat_pt = gs.reshape(point, (-1, self.sphere_metric.dim + 1))
flat_log = self.sphere_metric.log(flat_pt, flat_bp)
try:
log = gs.reshape(flat_log, base_point.shape)
except (RuntimeError, check_tf_error(ValueError, "InvalidArgumentError")):
log = gs.reshape(flat_log, point.shape)
return log
def curvature(self, tangent_vec_a, tangent_vec_b, tangent_vec_c, base_point):
r"""Compute the curvature.
For three tangent vectors at a base point :math:`x,y,z`,
the curvature is defined by
:math:`R(X, Y)Z = \nabla_{[X,Y]}Z
- \nabla_X\nabla_Y Z + - \nabla_Y\nabla_X Z`, where :math:`\nabla`
is the Levi-Civita connection. In the case of the hypersphere,
we have the closed formula
:math:`R(X,Y)Z = \langle X, Z \rangle Y - \langle Y,Z \rangle X`.
Parameters
----------
tangent_vec_a : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
tangent_vec_b : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
tangent_vec_c : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
base_point : array-like, shape=[..., k_landmarks, m_ambient]
Point on the group. Optional, default is the identity.
Returns
-------
curvature : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
"""
max_shape = base_point.shape
for arg in [tangent_vec_a, tangent_vec_b, tangent_vec_c]:
if arg.ndim >= 3:
max_shape = arg.shape
flat_shape = (-1, self.sphere_metric.dim + 1)
flat_a = gs.reshape(tangent_vec_a, flat_shape)
flat_b = gs.reshape(tangent_vec_b, flat_shape)
flat_c = gs.reshape(tangent_vec_c, flat_shape)
flat_bp = gs.reshape(base_point, flat_shape)
curvature = self.sphere_metric.curvature(flat_a, flat_b, flat_c, flat_bp)
curvature = gs.reshape(curvature, max_shape)
return curvature
def curvature_derivative(
self,
tangent_vec_a,
tangent_vec_b=None,
tangent_vec_c=None,
tangent_vec_d=None,
base_point=None,
):
r"""Compute the covariant derivative of the curvature.
For four vectors fields :math:`H|_P = tangent_vec_a, X|_P =
tangent_vec_b, Y|_P = tangent_vec_c, Z|_P = tangent_vec_d` with
tangent vector value specified in argument at the base point `P`,
the covariant derivative of the curvature
:math:`(\nabla_H R)(X, Y) Z |_P` is computed at the base point P.
Since the sphere is a constant curvature space this
vanishes identically.
Parameters
----------
tangent_vec_a : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point` along which the curvature is
derived.
tangent_vec_b : array-like, shape=[..., k_landmarks, m_ambient]
Unused tangent vector at `base_point` (since curvature derivative
vanishes).
tangent_vec_c : array-like, shape=[..., k_landmarks, m_ambient]
Unused tangent vector at `base_point` (since curvature derivative
vanishes).
tangent_vec_d : array-like, shape=[..., k_landmarks, m_ambient]
Unused tangent vector at `base_point` (since curvature derivative
vanishes).
base_point : array-like, shape=[..., k_landmarks, m_ambient]
Unused point on the group.
Returns
-------
curvature_derivative : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at base point.
"""
return gs.zeros_like(tangent_vec_a)
def parallel_transport(self, tangent_vec_a, tangent_vec_b, base_point):
"""Compute the Riemannian parallel transport of a tangent vector.
Parameters
----------
tangent_vec_a : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at a base point.
tangent_vec_b : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at a base point.
base_point : array-like, shape=[..., k_landmarks, m_ambient]
Point on the pre-shape space.
Returns
-------
transported : array-like, shape=[..., k_landmarks, m_ambient]
Point on the pre-shape space equal to the Riemannian exponential
of tangent_vec at the base point.
"""
max_shape = (
tangent_vec_a.shape if tangent_vec_a.ndim == 3 else tangent_vec_b.shape
)
flat_bp = gs.reshape(base_point, (-1, self.sphere_metric.dim + 1))
flat_tan_a = gs.reshape(tangent_vec_a, (-1, self.sphere_metric.dim + 1))
flat_tan_b = gs.reshape(tangent_vec_b, (-1, self.sphere_metric.dim + 1))
flat_transport = self.sphere_metric.parallel_transport(
flat_tan_a, flat_tan_b, flat_bp
)
return gs.reshape(flat_transport, max_shape)
class KendallShapeMetric(QuotientMetric):
"""Quotient metric on the shape space.
The Kendall shape space is obtained by taking the quotient of the
pre-shape space by the space of rotations of the ambient space.
Parameters
----------
k_landmarks : int
Number of landmarks
m_ambient : int
Number of coordinates of each landmark.
"""
def __init__(self, k_landmarks, m_ambient):
bundle = PreShapeSpace(k_landmarks, m_ambient)
super(KendallShapeMetric, self).__init__(
fiber_bundle=bundle, dim=bundle.dim - int(m_ambient * (m_ambient - 1) / 2)
)
def directional_curvature_derivative(
self, tangent_vec_a, tangent_vec_b, base_point=None
):
r"""Compute the covariant derivative of the directional curvature.
For two vectors fields :math:`X|_P = tangent_vec_a, Y|_P =
tangent_vec_b` with tangent vector value specified in argument at the
base point `P`, the covariant derivative (in the direction 'X')
:math:`(\nabla_X R_Y)(X) |_P = (\nabla_X R)(Y, X) Y |_P` of the
directional curvature (in the direction `Y`)
:math:`R_Y(X) = R(Y, X) Y` is a quadratic tensor in 'X' and 'Y' that
plays an important role in the computation of the moments of the
empirical Fréchet mean [Pennec]_.
In more details, let :math:`X, Y` be the horizontal lift of parallel
vector fields extending the tangent vectors given in argument by
parallel transport in a neighborhood of the base-point P in the
base-space. Such vector fields verify :math:`\nabla^T_X X=0` and
:math:`\nabla^T_X^Y = A_X Y` using the connection :math:`\nabla^T`
of the total space. Then the covariant derivative of the
directional curvature tensor is given by :math:
`\nabla_X (R_Y(X)) = hor \nabla^T_X (R^T_Y(X)) - A_X( ver R^T_Y(X))
- 3 (\nabla_X^T A_Y A_X Y - A_X A_Y A_X Y )`, where :math:`R^T_Y(X)`
is the directional curvature tensor of the total space.
Parameters
----------
tangent_vec_a : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
tangent_vec_b : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at `base_point`.
base_point : array-like, shape=[..., k_landmarks, m_ambient]
Point on the group.
Returns
-------
curvature_derivative : array-like, shape=[..., k_landmarks, m_ambient]
Tangent vector at base point.
"""
horizontal_x = self.fiber_bundle.horizontal_projection(
tangent_vec_a, base_point
)
horizontal_y = self.fiber_bundle.horizontal_projection(
tangent_vec_b, base_point
)
(
nabla_x_a_y_a_x_y,
a_x_a_y_a_x_y,
_,
_,
_,
) = self.fiber_bundle.iterated_integrability_tensor_derivative_parallel(
horizontal_x, horizontal_y, base_point
)
return 3.0 * (nabla_x_a_y_a_x_y - a_x_a_y_a_x_y)
def parallel_transport(
self, tangent_vec_a, tangent_vec_b, base_point, n_steps=100, step="rk4"
):
r"""Compute the parallel transport of a tangent vec along a geodesic.
Approximation of the solution of the parallel transport of a tangent
vector a along the geodesic defined by :math:`t \mapsto exp_(
base_point)(t* tangent_vec_b)`.
Parameters
----------
tangent_vec_a : array-like, shape=[..., k, m]
Tangent vector at `base_point` to transport.
tangent_vec_b : array-like, shape=[..., k, m]
Tangent vector ar `base_point`, initial velocity of the geodesic to
transport along.
base_point : array-like, shape=[..., k, m]
Initial point of the geodesic.