-
Notifications
You must be signed in to change notification settings - Fork 175
/
simplicial.py
1774 lines (1476 loc) · 76.4 KB
/
simplicial.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
"""Persistent homology on point clouds or finite metric spaces."""
# License: GNU AGPLv3
from numbers import Real, Integral
from types import FunctionType
import numpy as np
from joblib import Parallel, delayed
from pyflagser import flagser_weighted
from scipy.sparse import coo_matrix
from scipy.spatial import Delaunay
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.metrics.pairwise import pairwise_distances
from sklearn.utils.validation import check_is_fitted
from ._utils import _postprocess_diagrams
from ..base import PlotterMixin
from ..externals.python import ripser, SparseRipsComplex, CechComplex
from ..plotting import plot_diagram
from ..utils._docs import adapt_fit_transform_docs
from ..utils.intervals import Interval
from ..utils.validation import validate_params, check_point_clouds
_AVAILABLE_RIPS_WEIGHTS = {
"DTM": {
"p": {"type": Real, "in": [1, 2, np.inf]},
"r": {"type": Real, "in": Interval(0, np.inf, closed="right")},
"n_neighbors": {"type": Integral,
"in": Interval(1, np.inf, closed="left")}
},
"general": {
"p": {"type": Real, "in": [1, 2, np.inf]},
}
}
@adapt_fit_transform_docs
class VietorisRipsPersistence(BaseEstimator, TransformerMixin, PlotterMixin):
""":ref:`Persistence diagrams <persistence_diagram>` resulting from
:ref:`Vietoris–Rips filtrations
<vietoris-rips_complex_and_vietoris-rips_persistence>`.
Given a :ref:`point cloud <distance_matrices_and_point_clouds>` in
Euclidean space, an abstract :ref:`metric space
<distance_matrices_and_point_clouds>` encoded by a distance matrix, or the
adjacency matrix of a weighted undirected graph, information about the
appearance and disappearance of topological features (technically,
:ref:`homology classes <homology_and_cohomology>`) of various dimensions
and at different scales is summarised in the corresponding persistence
diagram.
**Important note**:
- Persistence diagrams produced by this class must be interpreted with
care due to the presence of padding triples which carry no
information. See :meth:`transform` for additional information.
Parameters
----------
metric : string or callable, optional, default: ``"euclidean"``
If set to ``"precomputed"``, input data is to be interpreted as a
collection of distance matrices or of adjacency matrices of weighted
undirected graphs. Otherwise, input data is to be interpreted as a
collection of point clouds (i.e. feature arrays), and `metric`
determines a rule with which to calculate distances between pairs of
points (i.e. row vectors). If `metric` is a string, it must be one of
the options allowed by :func:`scipy.spatial.distance.pdist` for its
metric parameter, or a metric listed in
:obj:`sklearn.pairwise.PAIRWISE_DISTANCE_FUNCTIONS`, including
``"euclidean"``, ``"manhattan"`` or ``"cosine"``. If `metric` is a
callable, it should take pairs of vectors (1D arrays) as input and, for
each two vectors in a pair, it should return a scalar indicating the
distance/dissimilarity between them.
metric_params : dict, optional, default: ``{}``
Additional parameters to be passed to the distance function.
homology_dimensions : list or tuple, optional, default: ``(0, 1)``
Dimensions (non-negative integers) of the topological features to be
detected.
coeff : int prime, optional, default: ``2``
Compute homology with coefficients in the prime field
:math:`\\mathbb{F}_p = \\{ 0, \\ldots, p - 1 \\}` where :math:`p`
equals `coeff`.
collapse_edges : bool, optional, default: ``False``
Whether to run the edge collapse algorithm in [2]_ prior to the
persistent homology computation (see the Notes). Can reduce the runtime
dramatically when the data or the maximum homology dimensions are
large.
max_edge_length : float, optional, default: ``numpy.inf``
Maximum value of the Vietoris–Rips filtration parameter. Points whose
distance is greater than this value will never be connected by an edge,
and topological features at scales larger than this value will not be
detected.
infinity_values : float or None, default: ``None``
Which death value to assign to features which are still alive at
filtration value `max_edge_length`. ``None`` means that this death
value is declared to be equal to `max_edge_length`.
reduced_homology : bool, optional, default: ``True``
If ``True``, the earliest-born triple in homology dimension 0 which has
infinite death is discarded from each diagram computed in
:meth:`transform`.
n_jobs : int or None, optional, default: ``None``
The number of jobs to use for the computation. ``None`` means 1 unless
in a :obj:`joblib.parallel_backend` context. ``-1`` means using all
processors.
Attributes
----------
infinity_values_ : float
Effective death value to assign to features which are still alive at
filtration value `max_edge_length`.
See also
--------
WeightedRipsPersistence, FlagserPersistence, SparseRipsPersistence,
WeakAlphaPersistence, EuclideanCechPersistence, ConsistentRescaling,
ConsecutiveRescaling
Notes
-----
`Ripser <https://github.com/Ripser/ripser>`_ [1]_ is used as a C++ backend
for computing Vietoris–Rips persistent homology. Python bindings were
modified for performance from the `ripser.py
<https://github.com/scikit-tda/ripser.py>`_ package.
`GUDHI <https://github.com/GUDHI/gudhi-devel>`_ is used as a C++ backend
for the edge collapse algorithm described in [2]_.
References
----------
.. [1] U. Bauer, "Ripser: efficient computation of Vietoris–Rips
persistence barcodes", 2019; `arXiv:1908.02518
<https://arxiv.org/abs/1908.02518>`_.
.. [2] J.-D. Boissonnat and S. Pritam, "Edge Collapse and Persistence of
Flag Complexes"; in *36th International Symposium on Computational
Geometry (SoCG 2020)*, pp. 19:1–19:15,
Schloss Dagstuhl-Leibniz–Zentrum für Informatik, 2020;
`DOI: 10.4230/LIPIcs.SoCG.2020.19
<https://doi.org/10.4230/LIPIcs.SoCG.2020.19>`_.
"""
_hyperparameters = {
"metric": {"type": (str, FunctionType)},
"metric_params": {"type": dict},
"homology_dimensions": {
"type": (list, tuple),
"of": {"type": int, "in": Interval(0, np.inf, closed="left")}
},
"collapse_edges": {"type": bool},
"coeff": {"type": int, "in": Interval(2, np.inf, closed="left")},
"max_edge_length": {"type": Real},
"infinity_values": {"type": (Real, type(None))},
"reduced_homology": {"type": bool}
}
def __init__(self, metric="euclidean", metric_params={},
homology_dimensions=(0, 1), collapse_edges=False, coeff=2,
max_edge_length=np.inf, infinity_values=None,
reduced_homology=True, n_jobs=None):
self.metric = metric
self.metric_params = metric_params
self.homology_dimensions = homology_dimensions
self.collapse_edges = collapse_edges
self.coeff = coeff
self.max_edge_length = max_edge_length
self.infinity_values = infinity_values
self.reduced_homology = reduced_homology
self.n_jobs = n_jobs
def _ripser_diagram(self, X):
Xdgms = ripser(
X, maxdim=self._max_homology_dimension,
thresh=self.max_edge_length, coeff=self.coeff, metric=self.metric,
metric_params=self.metric_params,
collapse_edges=self.collapse_edges
)["dgms"]
return Xdgms
def fit(self, X, y=None):
"""Calculate :attr:`infinity_values_`. Then, return the estimator.
This method is here to implement the usual scikit-learn API and hence
work in pipelines.
Parameters
----------
X : ndarray or list of length n_samples
Input data representing a collection of point clouds if `metric`
was not set to ``"precomputed"``, and of distance matrices or
adjacency matrices of weighted undirected graphs otherwise. Can be
either a 3D ndarray whose zeroth dimension has size ``n_samples``,
or a list containing ``n_samples`` 2D ndarrays/sparse matrices.
Point cloud arrays have shape ``(n_points, n_dimensions)``, and if
`X` is a list these shapes can vary between point clouds. If
`metric` was set to ``"precomputed"``, then:
- Diagonal entries indicate vertex weights, i.e. the filtration
parameters at which vertices appear.
- If entries of `X` are dense, only their upper diagonal
portions (including the diagonal) are considered.
- If entries of `X` are sparse, they do not need to be upper
diagonal or symmetric. If only one of entry (i, j) and (j, i)
is stored, its value is taken as the weight of the undirected
edge {i, j}. If both are stored, the value in the upper
diagonal is taken. Off-diagonal entries which are not
explicitly stored are treated as infinite, indicating absent
edges.
- Entries of `X` should be compatible with a filtration, i.e.
the value at index (i, j) should be no smaller than the
values at diagonal indices (i, i) and (j, j).
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
self : object
"""
validate_params(
self.get_params(), self._hyperparameters, exclude=["n_jobs"])
self._is_precomputed = self.metric == "precomputed"
check_point_clouds(X, accept_sparse=True,
distance_matrices=self._is_precomputed)
if self.infinity_values is None:
self.infinity_values_ = self.max_edge_length
else:
self.infinity_values_ = self.infinity_values
self._homology_dimensions = sorted(self.homology_dimensions)
self._max_homology_dimension = self._homology_dimensions[-1]
return self
def transform(self, X, y=None):
"""For each point cloud or distance matrix in `X`, compute the
relevant persistence diagram as an array of triples [b, d, q]. Each
triple represents a persistent topological feature in dimension q
(belonging to `homology_dimensions`) which is born at b and dies at d.
Only triples in which b < d are meaningful. Triples in which b and d
are equal ("diagonal elements") may be artificially introduced during
the computation for padding purposes, since the number of non-trivial
persistent topological features is typically not constant across
samples. They carry no information and hence should be effectively
ignored by any further computation.
Parameters
----------
X : ndarray or list of length n_samples
Input data representing a collection of point clouds if `metric`
was not set to ``"precomputed"``, and of distance matrices or
adjacency matrices of weighted undirected graphs otherwise. Can be
either a 3D ndarray whose zeroth dimension has size ``n_samples``,
or a list containing ``n_samples`` 2D ndarrays/sparse matrices.
Point cloud arrays have shape ``(n_points, n_dimensions)``, and if
`X` is a list these shapes can vary between point clouds. If
`metric` was set to ``"precomputed"``, then:
- Diagonal entries indicate vertex weights, i.e. the filtration
parameters at which vertices appear.
- If entries of `X` are dense, only their upper diagonal
portions (including the diagonal) are considered.
- If entries of `X` are sparse, they do not need to be upper
diagonal or symmetric. If only one of entry (i, j) and (j, i)
is stored, its value is taken as the weight of the undirected
edge {i, j}. If both are stored, the value in the upper
diagonal is taken. Off-diagonal entries which are not
explicitly stored are treated as infinite, indicating absent
edges.
- Entries of `X` should be compatible with a filtration, i.e.
the value at index (i, j) should be no smaller than the
values at diagonal indices (i, i) and (j, j).
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
Xt : ndarray of shape (n_samples, n_features, 3)
Array of persistence diagrams computed from the feature arrays or
distance matrices in `X`. ``n_features`` equals
:math:`\\sum_q n_q`, where :math:`n_q` is the maximum number of
topological features in dimension :math:`q` across all samples in
`X`.
"""
check_is_fitted(self)
X = check_point_clouds(X, accept_sparse=True,
distance_matrices=self._is_precomputed)
Xt = Parallel(n_jobs=self.n_jobs)(
delayed(self._ripser_diagram)(x) for x in X)
Xt = _postprocess_diagrams(
Xt, "ripser", self._homology_dimensions, self.infinity_values_,
self.reduced_homology
)
return Xt
@staticmethod
def plot(Xt, sample=0, homology_dimensions=None, plotly_params=None):
"""Plot a sample from a collection of persistence diagrams, with
homology in multiple dimensions.
Parameters
----------
Xt : ndarray of shape (n_samples, n_features, 3)
Collection of persistence diagrams, such as returned by
:meth:`transform`.
sample : int, optional, default: ``0``
Index of the sample in `Xt` to be plotted.
homology_dimensions : list, tuple or None, optional, default: ``None``
Which homology dimensions to include in the plot. ``None`` means
plotting all dimensions present in ``Xt[sample]``.
plotly_params : dict or None, optional, default: ``None``
Custom parameters to configure the plotly figure. Allowed keys are
``"traces"`` and ``"layout"``, and the corresponding values should
be dictionaries containing keyword arguments as would be fed to the
:meth:`update_traces` and :meth:`update_layout` methods of
:class:`plotly.graph_objects.Figure`.
Returns
-------
fig : :class:`plotly.graph_objects.Figure` object
Plotly figure.
"""
return plot_diagram(
Xt[sample], homology_dimensions=homology_dimensions,
plotly_params=plotly_params
)
@adapt_fit_transform_docs
class WeightedRipsPersistence(BaseEstimator, TransformerMixin, PlotterMixin):
""":ref:`Persistence diagrams <persistence_diagram>` resulting from
:ref:`weighted Vietoris–Rips filtrations <TODO>` as in [3]_.
Given a :ref:`point cloud <distance_matrices_and_point_clouds>` in
Euclidean space, an abstract :ref:`metric space
<distance_matrices_and_point_clouds>` encoded by a distance matrix, or the
adjacency matrix of a weighted undirected graph, information about the
appearance and disappearance of topological features (technically,
:ref:`homology classes <homology_and_cohomology>`) of various dimensions
and at different scales is summarised in the corresponding persistence
diagram.
Weighted (Vietoris–)Rips filtrations can be useful to highlight topological
features against outliers and noise. Among them, the distance-to-measure
(DTM) filtration is particularly suited to point clouds due to several
favourable properties. This implementation follows the general framework
described in [3]_. The idea is that, starting from a way to compute vertex
weights :math:`\\{w_i\\}_i` from an input point cloud/distance
matrix/adjacency matrix, a modified adjacency matrix is determined whose
diagonal entries are the :math:`\\{w_i\\}_i`, and whose edge weights are
.. math:: w_{ij} = \\begin{cases} \\max\\{ w_i, w_j \\} &\\text{if }
2\\mathrm{dist}_{ij} \\leq |w_i^p - w_j^p|^{\\frac{1}{p}}, \\\\
t &\\text{otherwise} \\end{cases}
where :math:`t` is the only positive root of
.. math:: 2 \\mathrm{dist}_{ij} = (t^p - w_i^p)^\\frac{1}{p} +
(t^p - w_j^p)^\\frac{1}{p}
and :math:`p` is a parameter (see `metric_params`). The modified adjacency
matrices are then treated exactly as in :class:`VietorisRipsPersistence`.
**Important notes**:
- Vertex and edge weights are twice the ones in [3]_ so that the same
results as :class:`VietorisRipsPersistence` are obtained when all
vertex weights are zero.
- Persistence diagrams produced by this class must be interpreted with
care due to the presence of padding triples which carry no
information. See :meth:`transform` for additional information.
Parameters
----------
metric : string or callable, optional, default: ``"euclidean"``
If set to ``"precomputed"``, input data is to be interpreted as a
collection of distance matrices or of adjacency matrices of weighted
undirected graphs. Otherwise, input data is to be interpreted as a
collection of point clouds (i.e. feature arrays), and `metric`
determines a rule with which to calculate distances between pairs of
points (i.e. row vectors). If `metric` is a string, it must be one of
the options allowed by :func:`scipy.spatial.distance.pdist` for its
metric parameter, or a metric listed in
:obj:`sklearn.pairwise.PAIRWISE_DISTANCE_FUNCTIONS`, including
``"euclidean"``, ``"manhattan"`` or ``"cosine"``. If `metric` is a
callable, it should take pairs of vectors (1D arrays) as input and, for
each two vectors in a pair, it should return a scalar indicating the
distance/dissimilarity between them.
metric_params : dict, optional, default: ``{}``
Additional parameters to be passed to the distance function.
homology_dimensions : list or tuple, optional, default: ``(0, 1)``
Dimensions (non-negative integers) of the topological features to be
detected.
weights : ``"DTM"`` or callable, optional, default: ``"DTM"``
Function that will be applied to each input point cloud/distance
matrix/adjacency matrix to compute a 1D array of vertex weights for the
the modified adjacency matrices. The default ``"DTM"`` denotes the
empirical distance-to-measure function defined, following [3]_, by
.. math:: w(x) = 2\\left(\\frac{1}{n+1} \\sum_{k=1}^n
\\mathrm{dist}(x, x_k)^r\\right)^{1/r}.
Here, :math:`\\mathrm{dist}` is the distance metric used, :math:`x_k`
is the :math:`k`-th :math:`\\mathrm{dist}`-nearest neighbour of
:math:`x` (:math:`x` is not considered a neighbour of itself),
:math:`n` is the number of nearest neighbors to include, and :math:`r`
is a parameter (see `weight_params`). If a callable, it must return
non-negative 1D arrays.
weight_params : dict, optional, default: ``None``
Additional parameters for the weighted filtration. ``"p"`` determines
the power to be used in computing edge weights from vertex weights. It
can be one of ``1``, ``2`` or ``np.inf`` and defaults to ``1``. If
`weights` is ``"DTM"``, the additional keys ``"r"`` (default: ``2``)
and ``"n_neighbors"`` (default: ``3``) are available (see `weights`,
where the latter corresponds to :math:`n`).
coeff : int prime, optional, default: ``2``
Compute homology with coefficients in the prime field
:math:`\\mathbb{F}_p = \\{ 0, \\ldots, p - 1 \\}` where :math:`p`
equals `coeff`.
collapse_edges : bool, optional, default: ``False``
Whether to run the edge collapse algorithm in [2]_ prior to the
persistent homology computation (see the Notes). Can reduce the runtime
dramatically when the data or the maximum homology dimensions are
large.
max_edge_weight : float, optional, default: ``numpy.inf``
Maximum value of the filtration parameter in the modified adjacency
matrix. Edges with weight greater than this value will be considered
absent.
infinity_values : float or None, default: ``None``
Which death value to assign to features which are still alive at
filtration value `max_edge_weight`. ``None`` means that this death
value is declared to be equal to `max_edge_weight`.
reduced_homology : bool, optional, default: ``True``
If ``True``, the earliest-born triple in homology dimension 0 which has
infinite death is discarded from each diagram computed in
:meth:`transform`.
n_jobs : int or None, optional, default: ``None``
The number of jobs to use for the computation. ``None`` means 1 unless
in a :obj:`joblib.parallel_backend` context. ``-1`` means using all
processors.
Attributes
----------
infinity_values_ : float
Effective death value to assign to features which are still alive at
filtration value `max_edge_weight`.
effective_weight_params_ : dict
Effective parameters involved in computing the weighted Rips
filtration.
See also
--------
VietorisRipsPersistence, SparseRipsPersistence, FlagserPersistence,
WeakAlphaPersistence, EuclideanCechPersistence, ConsistentRescaling,
ConsecutiveRescaling
Notes
-----
`Ripser <https://github.com/Ripser/ripser>`_ [1]_ is used as a C++ backend
for computing Vietoris–Rips persistent homology. Python bindings were
modified for performance from the `ripser.py
<https://github.com/scikit-tda/ripser.py>`_ package.
`GUDHI <https://github.com/GUDHI/gudhi-devel>`_ is used as a C++ backend
for the edge collapse algorithm described in [2]_.
References
----------
.. [1] U. Bauer, "Ripser: efficient computation of Vietoris–Rips
persistence barcodes", 2019; `arXiv:1908.02518
<https://arxiv.org/abs/1908.02518>`_.
.. [2] J.-D. Boissonnat and S. Pritam, "Edge Collapse and Persistence of
Flag Complexes"; in *36th International Symposium on Computational
Geometry (SoCG 2020)*, pp. 19:1–19:15,
Schloss Dagstuhl-Leibniz–Zentrum für Informatik, 2020;
`DOI: 10.4230/LIPIcs.SoCG.2020.19
<https://doi.org/10.4230/LIPIcs.SoCG.2020.19>`_.
.. [3] H. Anai et al, "DTM-Based Filtrations"; in *Topological Data
Analysis* (Abel Symposia, vol 15), Springer, 2020;
`DOI: 10.1007/978-3-030-43408-3_2
<https://doi.org/10.1007/978-3-030-43408-3_2>`_.
"""
_hyperparameters = {
"metric": {"type": (str, FunctionType)},
"metric_params": {"type": dict},
"homology_dimensions": {
"type": (list, tuple),
"of": {"type": int, "in": Interval(0, np.inf, closed="left")}
},
"weights": {"type": (str, FunctionType)},
"weight_params": {"type": (dict, type(None))},
"collapse_edges": {"type": bool},
"coeff": {"type": int, "in": Interval(2, np.inf, closed="left")},
"max_edge_weight": {"type": Real},
"infinity_values": {"type": (Real, type(None))},
"reduced_homology": {"type": bool}
}
def __init__(self, metric="euclidean", metric_params={},
homology_dimensions=(0, 1), weights="DTM", weight_params=None,
collapse_edges=False, coeff=2, max_edge_weight=np.inf,
infinity_values=None, reduced_homology=True, n_jobs=None):
self.metric = metric
self.metric_params = metric_params
self.homology_dimensions = homology_dimensions
self.weights = weights
self.weight_params = weight_params
self.collapse_edges = collapse_edges
self.coeff = coeff
self.max_edge_weight = max_edge_weight
self.infinity_values = infinity_values
self.reduced_homology = reduced_homology
self.n_jobs = n_jobs
def _ripser_diagram(self, X):
if isinstance(self.weights, FunctionType):
weights = self.weights(X)
else:
weights = self.weights
Xdgms = ripser(
X, maxdim=self._max_homology_dimension,
thresh=self.max_edge_weight, coeff=self.coeff, metric=self.metric,
metric_params=self.metric_params, weights=weights,
weight_params=self.effective_weight_params_,
collapse_edges=self.collapse_edges
)["dgms"]
return Xdgms
def fit(self, X, y=None):
"""Calculate :attr:`infinity_values_`. Then, return the estimator.
This method is here to implement the usual scikit-learn API and hence
work in pipelines.
Parameters
----------
X : ndarray or list of length n_samples
Input data representing a collection of point clouds if `metric`
was not set to ``"precomputed"``, and of distance matrices or
adjacency matrices of weighted undirected graphs otherwise. Can be
either a 3D ndarray whose zeroth dimension has size ``n_samples``,
or a list containing ``n_samples`` 2D ndarrays/sparse matrices.
Point cloud arrays have shape ``(n_points, n_dimensions)``, and if
`X` is a list these shapes can vary between point clouds. If
`metric` was set to ``"precomputed"``, then:
- All entries of `X` should not contain infinities or negative
values (contrary to :class:`VietorisRipsPersistence`).
- The diagonals of entries of `X` are ignored (after the vertex
weights are computed, when `weights` is a callable).
- If entries of `X` are dense, only their upper diagonal
portions are considered.
- If entries of `X` are sparse, they do not need to be upper
diagonal or symmetric. If only one of entry (i, j) and (j, i)
is stored, its value is taken as the weight of the undirected
edge {i, j}. If both are stored, the value in the upper
diagonal is taken. Off-diagonal entries which are not
explicitly stored are treated as infinite, indicating absent
edges.
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
self : object
"""
validate_params(
self.get_params(), self._hyperparameters, exclude=["n_jobs"])
if isinstance(self.weights, str) and self.weights != "DTM":
raise ValueError(f"'{self.weights}' passed for `weights` but the "
f"only allowed string is 'DTM'.")
self.effective_weight_params_ = {"p": 1}
if self.weights == "DTM":
key = "DTM"
self.effective_weight_params_.update({"n_neighbors": 3, "r": 2})
else:
key = "general"
if self.weight_params is not None:
self.effective_weight_params_.update(self.weight_params)
validate_params(self.effective_weight_params_,
_AVAILABLE_RIPS_WEIGHTS[key])
self._is_precomputed = self.metric == "precomputed"
check_point_clouds(X, accept_sparse=True, force_all_finite=True,
distance_matrices=self._is_precomputed)
if self.infinity_values is None:
self.infinity_values_ = self.max_edge_weight
else:
self.infinity_values_ = self.infinity_values
self._homology_dimensions = sorted(self.homology_dimensions)
self._max_homology_dimension = self._homology_dimensions[-1]
return self
def transform(self, X, y=None):
"""For each point cloud or distance matrix in `X`, compute the
relevant persistence diagram as an array of triples [b, d, q]. Each
triple represents a persistent topological feature in dimension q
(belonging to `homology_dimensions`) which is born at b and dies at d.
Only triples in which b < d are meaningful. Triples in which b and d
are equal ("diagonal elements") may be artificially introduced during
the computation for padding purposes, since the number of non-trivial
persistent topological features is typically not constant across
samples. They carry no information and hence should be effectively
ignored by any further computation.
Parameters
----------
X : ndarray or list of length n_samples
Input data representing a collection of point clouds if `metric`
was not set to ``"precomputed"``, and of distance matrices or
adjacency matrices of weighted undirected graphs otherwise. Can be
either a 3D ndarray whose zeroth dimension has size ``n_samples``,
or a list containing ``n_samples`` 2D ndarrays/sparse matrices.
Point cloud arrays have shape ``(n_points, n_dimensions)``, and if
`X` is a list these shapes can vary between point clouds. If
`metric` was set to ``"precomputed"``, then:
- All entries of `X` should not contain infinities or negative
values (contrary to :class:`VietorisRipsPersistence`).
- The diagonals of entries of `X` are ignored (after the vertex
weights are computed, when `weights` is a callable).
- If entries of `X` are dense, only their upper diagonal
portions are considered.
- If entries of `X` are sparse, they do not need to be upper
diagonal or symmetric. If only one of entry (i, j) and (j, i)
is stored, its value is taken as the weight of the undirected
edge {i, j}. If both are stored, the value in the upper
diagonal is taken. Off-diagonal entries which are not
explicitly stored are treated as infinite, indicating absent
edges.
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
Xt : ndarray of shape (n_samples, n_features, 3)
Array of persistence diagrams computed from the feature arrays or
distance matrices in `X`. ``n_features`` equals
:math:`\\sum_q n_q`, where :math:`n_q` is the maximum number of
topological features in dimension :math:`q` across all samples in
`X`.
"""
check_is_fitted(self)
X = check_point_clouds(X, accept_sparse=True, force_all_finite=True,
distance_matrices=self._is_precomputed)
Xt = Parallel(n_jobs=self.n_jobs)(
delayed(self._ripser_diagram)(x) for x in X)
Xt = _postprocess_diagrams(
Xt, "ripser", self._homology_dimensions, self.infinity_values_,
self.reduced_homology
)
return Xt
@staticmethod
def plot(Xt, sample=0, homology_dimensions=None, plotly_params=None):
"""Plot a sample from a collection of persistence diagrams, with
homology in multiple dimensions.
Parameters
----------
Xt : ndarray of shape (n_samples, n_features, 3)
Collection of persistence diagrams, such as returned by
:meth:`transform`.
sample : int, optional, default: ``0``
Index of the sample in `Xt` to be plotted.
homology_dimensions : list, tuple or None, optional, default: ``None``
Which homology dimensions to include in the plot. ``None`` means
plotting all dimensions present in ``Xt[sample]``.
plotly_params : dict or None, optional, default: ``None``
Custom parameters to configure the plotly figure. Allowed keys are
``"traces"`` and ``"layout"``, and the corresponding values should
be dictionaries containing keyword arguments as would be fed to the
:meth:`update_traces` and :meth:`update_layout` methods of
:class:`plotly.graph_objects.Figure`.
Returns
-------
fig : :class:`plotly.graph_objects.Figure` object
Plotly figure.
"""
return plot_diagram(
Xt[sample], homology_dimensions=homology_dimensions,
plotly_params=plotly_params
)
@adapt_fit_transform_docs
class SparseRipsPersistence(BaseEstimator, TransformerMixin, PlotterMixin):
""":ref:`Persistence diagrams <persistence_diagram>` resulting from
:ref:`Sparse Vietoris–Rips filtrations
<vietoris-rips_complex_and_vietoris-rips_persistence>`.
Given a :ref:`point cloud <distance_matrices_and_point_clouds>` in
Euclidean space, or an abstract :ref:`metric space
<distance_matrices_and_point_clouds>` encoded by a distance matrix,
information about the appearance and disappearance of topological features
(technically, :ref:`homology classes <homology_and_cohomology>`) of various
dimensions and at different scales is summarised in the corresponding
persistence diagram.
**Important note**:
- Persistence diagrams produced by this class must be interpreted with
care due to the presence of padding triples which carry no
information. See :meth:`transform` for additional information.
Parameters
----------
metric : string or callable, optional, default: ``"euclidean"``
If set to ``"precomputed"``, input data is to be interpreted as a
collection of distance matrices. Otherwise, input data is to be
interpreted as a collection of point clouds (i.e. feature arrays), and
`metric` determines a rule with which to calculate distances between
pairs of instances (i.e. rows) in these arrays. If `metric` is a
string, it must be one of the options allowed by
:func:`scipy.spatial.distance.pdist` for its metric parameter, or a
metric listed in :obj:`sklearn.pairwise.PAIRWISE_DISTANCE_FUNCTIONS`,
including "euclidean", "manhattan", or "cosine". If `metric` is a
callable, it is called on each pair of instances and the resulting
value recorded. The callable should take two arrays from the entry in
`X` as input, and return a value indicating the distance between them.
homology_dimensions : list or tuple, optional, default: ``(0, 1)``
Dimensions (non-negative integers) of the topological features to be
detected.
coeff : int prime, optional, default: ``2``
Compute homology with coefficients in the prime field
:math:`\\mathbb{F}_p = \\{ 0, \\ldots, p - 1 \\}` where :math:`p`
equals `coeff`.
epsilon : float between 0. and 1., optional, default: ``0.1``
Parameter controlling the approximation to the exact Vietoris–Rips
filtration. If set to `0.`, :class:`SparseRipsPersistence` leads to the
same results as :class:`VietorisRipsPersistence` but is slower.
max_edge_length : float, optional, default: ``numpy.inf``
Maximum value of the Sparse Rips filtration parameter. Points whose
distance is greater than this value will never be connected by an edge,
and topological features at scales larger than this value will not be
detected.
infinity_values : float or None, default: ``None``
Which death value to assign to features which are still alive at
filtration value `max_edge_length`. ``None`` means that this death
value is declared to be equal to `max_edge_length`.
reduced_homology : bool, optional, default: ``True``
If ``True``, the earliest-born triple in homology dimension 0 which has
infinite death is discarded from each diagram computed in
:meth:`transform`.
n_jobs : int or None, optional, default: ``None``
The number of jobs to use for the computation. ``None`` means 1 unless
in a :obj:`joblib.parallel_backend` context. ``-1`` means using all
processors.
Attributes
----------
infinity_values_ : float
Effective death value to assign to features which are still alive at
filtration value `max_edge_length`. Set in :meth:`fit`.
See also
--------
VietorisRipsPersistence, WeightedRipsPersistence, FlagserPersistence,
WeakAlphaPersistence, EuclideanCechPersistence, ConsistentRescaling,
ConsecutiveRescaling
Notes
-----
`GUDHI <https://github.com/GUDHI/gudhi-devel>`_ is used as a C++ backend
for computing sparse Vietoris–Rips persistent homology [1]_. Python
bindings were modified for performance.
References
----------
.. [1] C. Maria, "Persistent Cohomology", 2020; `GUDHI User and Reference
Manual <http://gudhi.gforge.inria.fr/doc/3.1.0/group__persistent__\
cohomology.html>`_.
"""
_hyperparameters = {
"metric": {"type": (str, FunctionType)},
"homology_dimensions": {
"type": (list, tuple),
"of": {"type": int, "in": Interval(0, np.inf, closed="left")}
},
"coeff": {"type": int, "in": Interval(2, np.inf, closed="left")},
"epsilon": {"type": Real, "in": Interval(0, 1, closed="both")},
"max_edge_length": {"type": Real},
"infinity_values": {"type": (Real, type(None))},
"reduced_homology": {"type": bool}
}
def __init__(self, metric="euclidean", homology_dimensions=(0, 1),
coeff=2, epsilon=0.1, max_edge_length=np.inf,
infinity_values=None, reduced_homology=True, n_jobs=None):
self.metric = metric
self.homology_dimensions = homology_dimensions
self.coeff = coeff
self.epsilon = epsilon
self.max_edge_length = max_edge_length
self.infinity_values = infinity_values
self.reduced_homology = reduced_homology
self.n_jobs = n_jobs
def _gudhi_diagram(self, X):
Xdgm = pairwise_distances(X, metric=self.metric)
sparse_rips_complex = SparseRipsComplex(
distance_matrix=Xdgm, max_edge_length=self.max_edge_length,
sparse=self.epsilon
)
simplex_tree = sparse_rips_complex.create_simplex_tree(
max_dimension=max(self._homology_dimensions) + 1
)
Xdgm = simplex_tree.persistence(
homology_coeff_field=self.coeff, min_persistence=0
)
return Xdgm
def fit(self, X, y=None):
"""Calculate :attr:`infinity_values_`. Then, return the estimator.
This method is here to implement the usual scikit-learn API and hence
work in pipelines.
Parameters
----------
X : ndarray or list of length n_samples
Input data representing a collection of point clouds if `metric`
was not set to ``"precomputed"``, and of distance matrices
otherwise. Can be either a 3D ndarray whose zeroth dimension has
size ``n_samples``, or a list containing ``n_samples`` 2D ndarrays.
Point cloud arrays have shape ``(n_points, n_dimensions)``, and if
`X` is a list these shapes can vary between point clouds. If
`metric` was set to ``"precomputed"``, each entry of `X` should be
compatible with a filtration, i.e. the value at index (i, j) should
be no smaller than the values at diagonal indices (i, i) and
(j, j).
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
self : object
"""
validate_params(
self.get_params(), self._hyperparameters, exclude=["n_jobs"])
self._is_precomputed = self.metric == "precomputed"
check_point_clouds(X, accept_sparse=True,
distance_matrices=self._is_precomputed)
if self.infinity_values is None:
self.infinity_values_ = self.max_edge_length
else:
self.infinity_values_ = self.infinity_values
self._homology_dimensions = sorted(self.homology_dimensions)
self._max_homology_dimension = self._homology_dimensions[-1]
return self
def transform(self, X, y=None):
"""For each point cloud or distance matrix in `X`, compute the
relevant persistence diagram as an array of triples [b, d, q]. Each
triple represents a persistent topological feature in dimension q
(belonging to `homology_dimensions`) which is born at b and dies at d.
Only triples in which b < d are meaningful. Triples in which b and d
are equal ("diagonal elements") may be artificially introduced during
the computation for padding purposes, since the number of non-trivial
persistent topological features is typically not constant across
samples. They carry no information and hence should be effectively
ignored by any further computation.
Parameters
----------
X : ndarray or list of length n_samples
Input data representing a collection of point clouds if `metric`
was not set to ``"precomputed"``, and of distance matrices
otherwise. Can be either a 3D ndarray whose zeroth dimension has
size ``n_samples``, or a list containing ``n_samples`` 2D ndarrays.
Point cloud arrays have shape ``(n_points, n_dimensions)``, and if
`X` is a list these shapes can vary between point clouds. If
`metric` was set to ``"precomputed"``, each entry of `X` should be
compatible with a filtration, i.e. the value at index (i, j) should
be no smaller than the values at diagonal indices (i, i) and
(j, j).
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
Xt : ndarray of shape (n_samples, n_features, 3)
Array of persistence diagrams computed from the feature arrays or
distance matrices in `X`. ``n_features`` equals
:math:`\\sum_q n_q`, where :math:`n_q` is the maximum number of
topological features in dimension :math:`q` across all samples in
`X`.
"""
check_is_fitted(self)
X = check_point_clouds(X, accept_sparse=True,
distance_matrices=self._is_precomputed)
Xt = Parallel(n_jobs=self.n_jobs)(
delayed(self._gudhi_diagram)(x) for x in X)
Xt = _postprocess_diagrams(
Xt, "gudhi", self._homology_dimensions, self.infinity_values_,
self.reduced_homology
)
return Xt
@staticmethod
def plot(Xt, sample=0, homology_dimensions=None, plotly_params=None):
"""Plot a sample from a collection of persistence diagrams, with
homology in multiple dimensions.
Parameters
----------
Xt : ndarray of shape (n_samples, n_features, 3)
Collection of persistence diagrams, such as returned by
:meth:`transform`.
sample : int, optional, default: ``0``
Index of the sample in `Xt` to be plotted.
homology_dimensions : list, tuple or None, optional, default: ``None``
Which homology dimensions to include in the plot. ``None`` means
plotting all dimensions present in ``Xt[sample]``.
plotly_params : dict or None, optional, default: ``None``
Custom parameters to configure the plotly figure. Allowed keys are
``"traces"`` and ``"layout"``, and the corresponding values should
be dictionaries containing keyword arguments as would be fed to the
:meth:`update_traces` and :meth:`update_layout` methods of
:class:`plotly.graph_objects.Figure`.
Returns
-------