multipers 2.4.0b1__cp312-cp312-macosx_11_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. multipers/.dylibs/libboost_timer.dylib +0 -0
  2. multipers/.dylibs/libc++.1.0.dylib +0 -0
  3. multipers/.dylibs/libtbb.12.17.dylib +0 -0
  4. multipers/__init__.py +33 -0
  5. multipers/_signed_measure_meta.py +426 -0
  6. multipers/_slicer_meta.py +231 -0
  7. multipers/array_api/__init__.py +62 -0
  8. multipers/array_api/numpy.py +124 -0
  9. multipers/array_api/torch.py +133 -0
  10. multipers/data/MOL2.py +458 -0
  11. multipers/data/UCR.py +18 -0
  12. multipers/data/__init__.py +1 -0
  13. multipers/data/graphs.py +466 -0
  14. multipers/data/immuno_regions.py +27 -0
  15. multipers/data/minimal_presentation_to_st_bf.py +0 -0
  16. multipers/data/pytorch2simplextree.py +91 -0
  17. multipers/data/shape3d.py +101 -0
  18. multipers/data/synthetic.py +113 -0
  19. multipers/distances.py +202 -0
  20. multipers/filtration_conversions.pxd +736 -0
  21. multipers/filtration_conversions.pxd.tp +226 -0
  22. multipers/filtrations/__init__.py +21 -0
  23. multipers/filtrations/density.py +529 -0
  24. multipers/filtrations/filtrations.py +480 -0
  25. multipers/filtrations.pxd +534 -0
  26. multipers/filtrations.pxd.tp +332 -0
  27. multipers/function_rips.cpython-312-darwin.so +0 -0
  28. multipers/function_rips.pyx +104 -0
  29. multipers/grids.cpython-312-darwin.so +0 -0
  30. multipers/grids.pyx +538 -0
  31. multipers/gudhi/Persistence_slices_interface.h +213 -0
  32. multipers/gudhi/Simplex_tree_interface.h +274 -0
  33. multipers/gudhi/Simplex_tree_multi_interface.h +648 -0
  34. multipers/gudhi/gudhi/Bitmap_cubical_complex.h +450 -0
  35. multipers/gudhi/gudhi/Bitmap_cubical_complex_base.h +1070 -0
  36. multipers/gudhi/gudhi/Bitmap_cubical_complex_periodic_boundary_conditions_base.h +579 -0
  37. multipers/gudhi/gudhi/Debug_utils.h +52 -0
  38. multipers/gudhi/gudhi/Degree_rips_bifiltration.h +2307 -0
  39. multipers/gudhi/gudhi/Dynamic_multi_parameter_filtration.h +2524 -0
  40. multipers/gudhi/gudhi/Fields/Multi_field.h +453 -0
  41. multipers/gudhi/gudhi/Fields/Multi_field_operators.h +460 -0
  42. multipers/gudhi/gudhi/Fields/Multi_field_shared.h +444 -0
  43. multipers/gudhi/gudhi/Fields/Multi_field_small.h +584 -0
  44. multipers/gudhi/gudhi/Fields/Multi_field_small_operators.h +490 -0
  45. multipers/gudhi/gudhi/Fields/Multi_field_small_shared.h +580 -0
  46. multipers/gudhi/gudhi/Fields/Z2_field.h +391 -0
  47. multipers/gudhi/gudhi/Fields/Z2_field_operators.h +389 -0
  48. multipers/gudhi/gudhi/Fields/Zp_field.h +493 -0
  49. multipers/gudhi/gudhi/Fields/Zp_field_operators.h +384 -0
  50. multipers/gudhi/gudhi/Fields/Zp_field_shared.h +492 -0
  51. multipers/gudhi/gudhi/Flag_complex_edge_collapser.h +337 -0
  52. multipers/gudhi/gudhi/Matrix.h +2200 -0
  53. multipers/gudhi/gudhi/Multi_filtration/Multi_parameter_generator.h +1712 -0
  54. multipers/gudhi/gudhi/Multi_filtration/multi_filtration_conversions.h +237 -0
  55. multipers/gudhi/gudhi/Multi_filtration/multi_filtration_utils.h +225 -0
  56. multipers/gudhi/gudhi/Multi_parameter_filtered_complex.h +485 -0
  57. multipers/gudhi/gudhi/Multi_parameter_filtration.h +2643 -0
  58. multipers/gudhi/gudhi/Multi_persistence/Box.h +233 -0
  59. multipers/gudhi/gudhi/Multi_persistence/Line.h +309 -0
  60. multipers/gudhi/gudhi/Multi_persistence/Multi_parameter_filtered_complex_pcoh_interface.h +268 -0
  61. multipers/gudhi/gudhi/Multi_persistence/Persistence_interface_cohomology.h +159 -0
  62. multipers/gudhi/gudhi/Multi_persistence/Persistence_interface_matrix.h +463 -0
  63. multipers/gudhi/gudhi/Multi_persistence/Point.h +853 -0
  64. multipers/gudhi/gudhi/Off_reader.h +173 -0
  65. multipers/gudhi/gudhi/Persistence_matrix/Base_matrix.h +834 -0
  66. multipers/gudhi/gudhi/Persistence_matrix/Base_matrix_with_column_compression.h +838 -0
  67. multipers/gudhi/gudhi/Persistence_matrix/Boundary_matrix.h +833 -0
  68. multipers/gudhi/gudhi/Persistence_matrix/Chain_matrix.h +1367 -0
  69. multipers/gudhi/gudhi/Persistence_matrix/Id_to_index_overlay.h +1157 -0
  70. multipers/gudhi/gudhi/Persistence_matrix/Position_to_index_overlay.h +869 -0
  71. multipers/gudhi/gudhi/Persistence_matrix/RU_matrix.h +905 -0
  72. multipers/gudhi/gudhi/Persistence_matrix/allocators/entry_constructors.h +122 -0
  73. multipers/gudhi/gudhi/Persistence_matrix/base_pairing.h +260 -0
  74. multipers/gudhi/gudhi/Persistence_matrix/base_swap.h +288 -0
  75. multipers/gudhi/gudhi/Persistence_matrix/chain_pairing.h +170 -0
  76. multipers/gudhi/gudhi/Persistence_matrix/chain_rep_cycles.h +247 -0
  77. multipers/gudhi/gudhi/Persistence_matrix/chain_vine_swap.h +571 -0
  78. multipers/gudhi/gudhi/Persistence_matrix/columns/chain_column_extra_properties.h +182 -0
  79. multipers/gudhi/gudhi/Persistence_matrix/columns/column_dimension_holder.h +130 -0
  80. multipers/gudhi/gudhi/Persistence_matrix/columns/column_utilities.h +235 -0
  81. multipers/gudhi/gudhi/Persistence_matrix/columns/entry_types.h +312 -0
  82. multipers/gudhi/gudhi/Persistence_matrix/columns/heap_column.h +1092 -0
  83. multipers/gudhi/gudhi/Persistence_matrix/columns/intrusive_list_column.h +923 -0
  84. multipers/gudhi/gudhi/Persistence_matrix/columns/intrusive_set_column.h +914 -0
  85. multipers/gudhi/gudhi/Persistence_matrix/columns/list_column.h +930 -0
  86. multipers/gudhi/gudhi/Persistence_matrix/columns/naive_vector_column.h +1071 -0
  87. multipers/gudhi/gudhi/Persistence_matrix/columns/row_access.h +203 -0
  88. multipers/gudhi/gudhi/Persistence_matrix/columns/set_column.h +886 -0
  89. multipers/gudhi/gudhi/Persistence_matrix/columns/unordered_set_column.h +984 -0
  90. multipers/gudhi/gudhi/Persistence_matrix/columns/vector_column.h +1213 -0
  91. multipers/gudhi/gudhi/Persistence_matrix/index_mapper.h +58 -0
  92. multipers/gudhi/gudhi/Persistence_matrix/matrix_dimension_holders.h +227 -0
  93. multipers/gudhi/gudhi/Persistence_matrix/matrix_row_access.h +200 -0
  94. multipers/gudhi/gudhi/Persistence_matrix/ru_pairing.h +166 -0
  95. multipers/gudhi/gudhi/Persistence_matrix/ru_rep_cycles.h +319 -0
  96. multipers/gudhi/gudhi/Persistence_matrix/ru_vine_swap.h +562 -0
  97. multipers/gudhi/gudhi/Persistence_on_a_line.h +152 -0
  98. multipers/gudhi/gudhi/Persistence_on_rectangle.h +617 -0
  99. multipers/gudhi/gudhi/Persistent_cohomology/Field_Zp.h +118 -0
  100. multipers/gudhi/gudhi/Persistent_cohomology/Multi_field.h +173 -0
  101. multipers/gudhi/gudhi/Persistent_cohomology/Persistent_cohomology_column.h +128 -0
  102. multipers/gudhi/gudhi/Persistent_cohomology.h +769 -0
  103. multipers/gudhi/gudhi/Points_off_io.h +171 -0
  104. multipers/gudhi/gudhi/Projective_cover_kernel.h +379 -0
  105. multipers/gudhi/gudhi/Simple_object_pool.h +69 -0
  106. multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_iterators.h +559 -0
  107. multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_node_explicit_storage.h +83 -0
  108. multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_siblings.h +121 -0
  109. multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_star_simplex_iterators.h +277 -0
  110. multipers/gudhi/gudhi/Simplex_tree/filtration_value_utils.h +155 -0
  111. multipers/gudhi/gudhi/Simplex_tree/hooks_simplex_base.h +62 -0
  112. multipers/gudhi/gudhi/Simplex_tree/indexing_tag.h +27 -0
  113. multipers/gudhi/gudhi/Simplex_tree/serialization_utils.h +60 -0
  114. multipers/gudhi/gudhi/Simplex_tree/simplex_tree_options.h +105 -0
  115. multipers/gudhi/gudhi/Simplex_tree.h +3170 -0
  116. multipers/gudhi/gudhi/Slicer.h +848 -0
  117. multipers/gudhi/gudhi/Thread_safe_slicer.h +393 -0
  118. multipers/gudhi/gudhi/distance_functions.h +62 -0
  119. multipers/gudhi/gudhi/graph_simplicial_complex.h +104 -0
  120. multipers/gudhi/gudhi/multi_simplex_tree_helpers.h +147 -0
  121. multipers/gudhi/gudhi/persistence_interval.h +263 -0
  122. multipers/gudhi/gudhi/persistence_matrix_options.h +188 -0
  123. multipers/gudhi/gudhi/reader_utils.h +367 -0
  124. multipers/gudhi/gudhi/simple_mdspan.h +484 -0
  125. multipers/gudhi/gudhi/slicer_helpers.h +779 -0
  126. multipers/gudhi/tmp_h0_pers/mma_interface_h0.h +223 -0
  127. multipers/gudhi/tmp_h0_pers/naive_merge_tree.h +536 -0
  128. multipers/io.cpython-312-darwin.so +0 -0
  129. multipers/io.pyx +472 -0
  130. multipers/ml/__init__.py +0 -0
  131. multipers/ml/accuracies.py +90 -0
  132. multipers/ml/invariants_with_persistable.py +79 -0
  133. multipers/ml/kernels.py +176 -0
  134. multipers/ml/mma.py +713 -0
  135. multipers/ml/one.py +472 -0
  136. multipers/ml/point_clouds.py +352 -0
  137. multipers/ml/signed_measures.py +1667 -0
  138. multipers/ml/sliced_wasserstein.py +461 -0
  139. multipers/ml/tools.py +113 -0
  140. multipers/mma_structures.cpython-312-darwin.so +0 -0
  141. multipers/mma_structures.pxd +134 -0
  142. multipers/mma_structures.pyx +1483 -0
  143. multipers/mma_structures.pyx.tp +1126 -0
  144. multipers/multi_parameter_rank_invariant/diff_helpers.h +85 -0
  145. multipers/multi_parameter_rank_invariant/euler_characteristic.h +95 -0
  146. multipers/multi_parameter_rank_invariant/function_rips.h +317 -0
  147. multipers/multi_parameter_rank_invariant/hilbert_function.h +761 -0
  148. multipers/multi_parameter_rank_invariant/persistence_slices.h +149 -0
  149. multipers/multi_parameter_rank_invariant/rank_invariant.h +350 -0
  150. multipers/multiparameter_edge_collapse.py +41 -0
  151. multipers/multiparameter_module_approximation/approximation.h +2541 -0
  152. multipers/multiparameter_module_approximation/debug.h +107 -0
  153. multipers/multiparameter_module_approximation/format_python-cpp.h +292 -0
  154. multipers/multiparameter_module_approximation/utilities.h +428 -0
  155. multipers/multiparameter_module_approximation.cpython-312-darwin.so +0 -0
  156. multipers/multiparameter_module_approximation.pyx +286 -0
  157. multipers/ops.cpython-312-darwin.so +0 -0
  158. multipers/ops.pyx +231 -0
  159. multipers/pickle.py +89 -0
  160. multipers/plots.py +550 -0
  161. multipers/point_measure.cpython-312-darwin.so +0 -0
  162. multipers/point_measure.pyx +409 -0
  163. multipers/simplex_tree_multi.cpython-312-darwin.so +0 -0
  164. multipers/simplex_tree_multi.pxd +136 -0
  165. multipers/simplex_tree_multi.pyx +11719 -0
  166. multipers/simplex_tree_multi.pyx.tp +2102 -0
  167. multipers/slicer.cpython-312-darwin.so +0 -0
  168. multipers/slicer.pxd +2097 -0
  169. multipers/slicer.pxd.tp +263 -0
  170. multipers/slicer.pyx +13042 -0
  171. multipers/slicer.pyx.tp +1259 -0
  172. multipers/tensor/tensor.h +672 -0
  173. multipers/tensor.pxd +13 -0
  174. multipers/test.pyx +44 -0
  175. multipers/tests/__init__.py +70 -0
  176. multipers/torch/__init__.py +1 -0
  177. multipers/torch/diff_grids.py +240 -0
  178. multipers/torch/rips_density.py +310 -0
  179. multipers/vector_interface.pxd +46 -0
  180. multipers-2.4.0b1.dist-info/METADATA +131 -0
  181. multipers-2.4.0b1.dist-info/RECORD +184 -0
  182. multipers-2.4.0b1.dist-info/WHEEL +6 -0
  183. multipers-2.4.0b1.dist-info/licenses/LICENSE +21 -0
  184. multipers-2.4.0b1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,480 @@
1
+ from collections.abc import Sequence
2
+ from typing import Optional
3
+ from warnings import warn
4
+
5
+ import gudhi as gd
6
+ import numpy as np
7
+ from numpy.typing import ArrayLike
8
+ from scipy.spatial import KDTree
9
+
10
+ from multipers.array_api import api_from_tensor, api_from_tensors
11
+ from multipers.filtrations.density import DTM, available_kernels
12
+ from multipers.grids import compute_grid
13
+ from multipers.simplex_tree_multi import SimplexTreeMulti, SimplexTreeMulti_type
14
+ import multipers as _mp
15
+
16
+ try:
17
+ import pykeops
18
+
19
+ from multipers.filtrations.density import KDE
20
+ except ImportError:
21
+ from sklearn.neighbors import KernelDensity
22
+
23
+ warn("pykeops not found. Falling back to sklearn.")
24
+
25
+ def KDE(bandwidth, kernel, return_log):
26
+ assert return_log, "Sklearn returns log-density."
27
+ return KernelDensity(bandwidth=bandwidth, kernel=kernel)
28
+
29
+
30
+ def RipsLowerstar(
31
+ *,
32
+ points: Optional[ArrayLike] = None,
33
+ distance_matrix: Optional[ArrayLike] = None,
34
+ function: Optional[ArrayLike] = None,
35
+ threshold_radius: Optional[float] = None,
36
+ ):
37
+ """
38
+ Computes the Rips complex, with the usual rips filtration as a first parameter,
39
+ and the lower star multi filtration as other parameter.
40
+
41
+ Input:
42
+ - points or distance_matrix: ArrayLike
43
+ - function : ArrayLike of shape (num_data, num_parameters -1)
44
+ - threshold_radius: max edge length of the rips. Defaults at min(max(distance_matrix, axis=1)).
45
+ """
46
+ assert points is not None or distance_matrix is not None, (
47
+ "`points` or `distance_matrix` has to be given."
48
+ )
49
+ if distance_matrix is None:
50
+ api = api_from_tensor(points)
51
+ points = api.astensor(points)
52
+ D = api.cdist(points, points) # this may be slow...
53
+ else:
54
+ api = api_from_tensor(distance_matrix)
55
+ D = api.astensor(distance_matrix)
56
+
57
+ if threshold_radius is None:
58
+ threshold_radius = api.min(api.maxvalues(D, axis=1))
59
+ st = gd.SimplexTree.create_from_array(
60
+ api.asnumpy(D), max_filtration=threshold_radius
61
+ )
62
+ if function is None:
63
+ return SimplexTreeMulti(st, num_parameters=1)
64
+
65
+ function = api.astensor(function)
66
+ if function.ndim == 1:
67
+ function = function[:, None]
68
+ if function.ndim != 2:
69
+ raise ValueError(
70
+ f"""
71
+ `function.ndim` should be 0 or 1 . Got {function.ndim=}.{function=}
72
+ """
73
+ )
74
+ num_parameters = function.shape[1] + 1
75
+ st = SimplexTreeMulti(st, num_parameters=num_parameters)
76
+ for i in range(function.shape[1]):
77
+ st.fill_lowerstar(api.asnumpy(function[:, i]), parameter=1 + i)
78
+ if api.has_grad(D) or api.has_grad(function):
79
+ from multipers.grids import compute_grid
80
+
81
+ filtration_values = [D.ravel(), *[f for f in function.T]]
82
+ grid = compute_grid(filtration_values)
83
+ st = st.grid_squeeze(grid)
84
+ st._clean_filtration_grid()
85
+ return st
86
+
87
+
88
+ def RipsCodensity(
89
+ points: ArrayLike,
90
+ bandwidth: Optional[float] = None,
91
+ *,
92
+ return_log: bool = True,
93
+ dtm_mass: Optional[float] = None,
94
+ kernel: available_kernels = "gaussian",
95
+ threshold_radius: Optional[float] = None,
96
+ ):
97
+ """
98
+ Computes the Rips density filtration.
99
+ """
100
+ assert bandwidth is None or dtm_mass is None, (
101
+ "Density estimation is either via kernels or dtm."
102
+ )
103
+ if bandwidth is not None:
104
+ kde = KDE(bandwidth=bandwidth, kernel=kernel, return_log=return_log)
105
+ f = -kde.fit(points).score_samples(points)
106
+ elif dtm_mass is not None:
107
+ f = DTM(masses=[dtm_mass]).fit(points).score_samples(points)[0]
108
+ else:
109
+ raise ValueError("Bandwidth or DTM mass has to be given.")
110
+ return RipsLowerstar(points=points, function=f, threshold_radius=threshold_radius)
111
+
112
+
113
+ def DelaunayLowerstar(
114
+ points: ArrayLike,
115
+ function: ArrayLike,
116
+ *,
117
+ distance_matrix: Optional[ArrayLike] = None,
118
+ threshold_radius: Optional[float] = None,
119
+ reduce_degree: int = -1,
120
+ vineyard: Optional[bool] = None,
121
+ dtype=np.float64,
122
+ verbose: bool = False,
123
+ clear: bool = True,
124
+ flagify: bool = False,
125
+ ):
126
+ """
127
+ Computes the Function Delaunay bifiltration. Similar to RipsLowerstar, but most suited for low-dimensional euclidean data.
128
+ See [Delaunay bifiltrations of functions on point clouds, Alonso et al] https://doi.org/10.1137/1.9781611977912.173
129
+
130
+ Input:
131
+ - points or distance_matrix: ArrayLike
132
+ - function : ArrayLike of shape (num_data, )
133
+ - threshold_radius: max edge length of the rips. Defaults at min(max(distance_matrix, axis=1)).
134
+ """
135
+ from multipers.slicer import from_function_delaunay
136
+
137
+ if flagify and reduce_degree >= 0:
138
+ raise ValueError(
139
+ "Got {reduce_degree=} and {flagify=}. Cannot flagify with reduce degree."
140
+ )
141
+ assert distance_matrix is None, "Delaunay cannot be built from distance matrices"
142
+ if threshold_radius is not None:
143
+ raise NotImplementedError("Delaunay with threshold not implemented yet.")
144
+ api = api_from_tensors(points, function)
145
+ if not flagify and (api.has_grad(points) or api.has_grad(function)):
146
+ warn("Cannot keep points gradient unless using `flagify=True`.")
147
+ points = api.astensor(points)
148
+ function = api.astensor(function).squeeze()
149
+ assert function.ndim == 1, (
150
+ "Delaunay Lowerstar is only compatible with 1 additional parameter."
151
+ )
152
+ slicer = from_function_delaunay(
153
+ api.asnumpy(points),
154
+ api.asnumpy(function),
155
+ degree=reduce_degree,
156
+ vineyard=vineyard,
157
+ dtype=dtype,
158
+ verbose=verbose,
159
+ clear=clear,
160
+ )
161
+ if reduce_degree >= 0:
162
+ # Force resolution to avoid confusion with hilbert.
163
+ slicer = slicer.minpres(degree=reduce_degree, force=True)
164
+ if flagify:
165
+ from multipers.slicer import to_simplextree
166
+
167
+ slicer = to_simplextree(slicer)
168
+ slicer.flagify(2)
169
+
170
+ if api.has_grad(points) or api.has_grad(function):
171
+ distances = api.cdist(points, points) / 2
172
+ grid = compute_grid([distances.ravel(), function])
173
+ slicer = slicer.grid_squeeze(grid)
174
+ slicer = slicer._clean_filtration_grid()
175
+
176
+ return slicer
177
+
178
+
179
+ def DelaunayCodensity(
180
+ points: ArrayLike,
181
+ bandwidth: Optional[float] = None,
182
+ *,
183
+ return_log: bool = True,
184
+ dtm_mass: Optional[float] = None,
185
+ kernel: available_kernels = "gaussian",
186
+ threshold_radius: Optional[float] = None,
187
+ reduce_degree: int = -1,
188
+ vineyard: Optional[bool] = None,
189
+ dtype=np.float64,
190
+ verbose: bool = False,
191
+ clear: bool = True,
192
+ flagify: bool = False,
193
+ ):
194
+ """
195
+ TODO
196
+ """
197
+ assert bandwidth is None or dtm_mass is None, (
198
+ "Density estimation is either via kernels or dtm."
199
+ )
200
+ if bandwidth is not None:
201
+ kde = KDE(bandwidth=bandwidth, kernel=kernel, return_log=return_log)
202
+ f = -kde.fit(points).score_samples(points)
203
+ elif dtm_mass is not None:
204
+ f = DTM(masses=[dtm_mass]).fit(points).score_samples(points)[0]
205
+ else:
206
+ raise ValueError("Bandwidth or DTM mass has to be given.")
207
+ return DelaunayLowerstar(
208
+ points=points,
209
+ function=f,
210
+ threshold_radius=threshold_radius,
211
+ reduce_degree=reduce_degree,
212
+ vineyard=vineyard,
213
+ dtype=dtype,
214
+ verbose=verbose,
215
+ clear=clear,
216
+ flagify=flagify,
217
+ )
218
+
219
+
220
+ def Cubical(image: ArrayLike, **slicer_kwargs):
221
+ """
222
+ Computes the cubical filtration of an image.
223
+ The last axis dimention is interpreted as the number of parameters.
224
+
225
+ Input:
226
+ - image: ArrayLike of shape (*image_resolution, num_parameters)
227
+ - ** args : specify non-default slicer parameters
228
+ """
229
+ from multipers.slicer import from_bitmap
230
+
231
+ api = api_from_tensor(image)
232
+ image = api.astensor(image)
233
+ if api.has_grad(image):
234
+ img2 = image.reshape(-1, image.shape[-1]).T
235
+ grid = compute_grid(img2)
236
+ coord_img = np.empty(image.shape, dtype=np.int32)
237
+ slice_shape = image.shape[:-1]
238
+ for i in range(image.shape[-1]):
239
+ coord_img[..., i] = np.searchsorted(
240
+ api.asnumpy(grid[i]),
241
+ api.asnumpy(image[..., i]).reshape(-1),
242
+ ).reshape(slice_shape)
243
+ slicer = from_bitmap(coord_img, **slicer_kwargs)
244
+ slicer.filtration_grid = grid
245
+ slicer._clean_filtration_grid()
246
+ return slicer
247
+
248
+ return from_bitmap(image, **slicer_kwargs)
249
+
250
+
251
+ def DegreeRips(
252
+ *,
253
+ simplex_tree=None,
254
+ degrees=None,
255
+ points=None,
256
+ distance_matrix=None,
257
+ ks=None,
258
+ threshold_radius=None,
259
+ num=None,
260
+ squeeze_strategy="exact",
261
+ squeeze_resolution=None,
262
+ squeeze=True,
263
+ ):
264
+ """
265
+ The DegreeRips filtration.
266
+ """
267
+
268
+ if simplex_tree is None:
269
+ if distance_matrix is None:
270
+ if points is None:
271
+ raise ValueError(
272
+ "A simplextree, a distance matrix or a point cloud has to be given."
273
+ )
274
+ api = api_from_tensor(points)
275
+ points = api.astensor(points)
276
+ D = api.cdist(points, points)
277
+ else:
278
+ api = api_from_tensor(distance_matrix)
279
+ D = api.astensor(distance_matrix)
280
+
281
+ if threshold_radius is None:
282
+ threshold_radius = api.min(api.maxvalues(D, axis=1))
283
+ st = gd.SimplexTree.create_from_array(
284
+ api.asnumpy(D), max_filtration=threshold_radius
285
+ )
286
+ rips_filtration = api.unique(D.ravel())
287
+ else:
288
+ st = simplex_tree
289
+ rips_filtration = None
290
+
291
+ if ks is None or rips_filtration is None:
292
+ from warnings import warn
293
+
294
+ warn(
295
+ "(copy warning) Had to copy the rips to infer the `degrees` or recover the 1st filtration parameter."
296
+ )
297
+ _temp_st = _mp.SimplexTreeMulti(
298
+ st, num_parameters=1
299
+ ) # Gudhi is missing some functionality
300
+ if ks is None:
301
+ max_degree = (
302
+ np.bincount(_temp_st.get_simplices_of_dimension(1).ravel()).max() // 2
303
+ )
304
+ ks = (
305
+ np.arange(max_degree)
306
+ if num is None
307
+ else np.unique(np.linspace(0, max_degree, num, dtype=np.int32))
308
+ )
309
+ if rips_filtration is None:
310
+ rips_filtration = _mp.grids.compute_grid(_temp_st)[0]
311
+
312
+ from multipers.function_rips import get_degree_rips
313
+
314
+ st_multi = get_degree_rips(st, degrees=ks)
315
+ if squeeze:
316
+ F = [rips_filtration, ks.astype(np.float64)]
317
+ F = _mp.grids.compute_grid(
318
+ F, strategy=squeeze_strategy, resolution=squeeze_resolution
319
+ )
320
+ st_multi = st_multi.grid_squeeze(F)
321
+ st_multi.filtration_grid = (F[0], F[1] - F[1][-1]) # degrees are negative
322
+ return st_multi
323
+
324
+
325
+ def CoreDelaunay(
326
+ points: ArrayLike,
327
+ *,
328
+ beta: float = 1.0,
329
+ ks: Optional[Sequence[int]] = None,
330
+ precision: str = "safe",
331
+ verbose: bool = False,
332
+ max_alpha_square: float = float("inf"),
333
+ positive_degree: bool = False,
334
+ ) -> SimplexTreeMulti_type:
335
+ """
336
+ Computes the Delaunay core bifiltration of a point cloud presented in the paper "Core Bifiltration" https://arxiv.org/abs/2405.01214, and returns the (multi-critical) bifiltration as a SimplexTreeMulti. The Delaunay core bifiltration is an alpha complex version of the core bifiltration which is smaller in size. Moreover, along the horizontal line k=1, the Delaunay core bifiltration is identical to the alpha complex.
337
+
338
+ Input:
339
+ - points: The point cloud as an ArrayLike of shape (n, d) where n is the number of points and d is the dimension of the points.
340
+ - beta: The beta parameter for the Delaunay Core Bifiltration (default 1.0).
341
+ - ks: The list of k-values to include in the bifiltration (default None). If None, the k-values are set to [1, 2, ..., n] where n is the number of points in the point cloud. For large point clouds, it is recommended to set ks to a smaller list of k-values to reduce computation time. The values in ks must all be integers, positive, and less than or equal to the number of points in the point cloud.
342
+ - precision: The precision of the computation of the AlphaComplex, one of ['safe', 'exact', 'fast'] (default 'safe'). See the GUDHI documentation for more information.
343
+ - verbose: Whether to print progress messages (default False).
344
+ - max_alpha_square: The maximum squared alpha value to consider when createing the alpha complex (default inf). See the GUDHI documentation for more information.
345
+ """
346
+ points = np.asarray(points)
347
+ if ks is None:
348
+ ks = np.arange(1, len(points) + 1)
349
+ else:
350
+ ks = np.asarray(ks, dtype=int)
351
+ ks: np.ndarray
352
+
353
+ assert len(ks) > 0, "The parameter ks must contain at least one value."
354
+ assert np.all(ks > 0), "All values in ks must be positive."
355
+ assert np.all(ks <= len(points)), (
356
+ "All values in ks must be less than or equal to the number of points in the point cloud."
357
+ )
358
+ assert len(points) > 0, "The point cloud must contain at least one point."
359
+ assert points.ndim == 2, f"The point cloud must be a 2D array, got {points.ndim}D."
360
+ assert beta >= 0, f"The parameter beta must be positive, got {beta}."
361
+ assert precision in [
362
+ "safe",
363
+ "exact",
364
+ "fast",
365
+ ], f"""
366
+ The parameter precision must be one of ['safe', 'exact', 'fast'],
367
+ got {precision}.
368
+ """
369
+
370
+ if verbose:
371
+ print(
372
+ f"""Computing the Delaunay Core Bifiltration
373
+ of {len(points)} points in dimension {points.shape[1]}
374
+ with parameters:
375
+ """
376
+ )
377
+ print(f"\tbeta = {beta}")
378
+ print(f"\tks = {ks}")
379
+
380
+ if verbose:
381
+ print("Building the alpha complex...")
382
+ alpha_complex = gd.AlphaComplex(
383
+ points=points, precision=precision
384
+ ).create_simplex_tree(max_alpha_square=max_alpha_square)
385
+
386
+ if verbose:
387
+ print("Computing the k-nearest neighbor distances...")
388
+ knn_distances = KDTree(points).query(points, k=ks)[0]
389
+
390
+ max_dim = alpha_complex.dimension()
391
+ vertex_arrays_in_dimension = [[] for _ in range(max_dim + 1)]
392
+ squared_alphas_in_dimension = [[] for _ in range(max_dim + 1)]
393
+ for simplex, alpha_squared in alpha_complex.get_simplices():
394
+ dim = len(simplex) - 1
395
+ squared_alphas_in_dimension[dim].append(alpha_squared)
396
+ vertex_arrays_in_dimension[dim].append(simplex)
397
+
398
+ alphas_in_dimension = [
399
+ np.sqrt(np.array(alpha_squared, dtype=np.float64))
400
+ for alpha_squared in squared_alphas_in_dimension
401
+ ]
402
+ vertex_arrays_in_dimension = [
403
+ np.array(vertex_array, dtype=np.int32)
404
+ for vertex_array in vertex_arrays_in_dimension
405
+ ]
406
+
407
+ simplex_tree_multi = SimplexTreeMulti(
408
+ num_parameters=2, kcritical=True, dtype=np.float64
409
+ )
410
+
411
+ for dim, (vertex_array, alphas) in enumerate(
412
+ zip(vertex_arrays_in_dimension, alphas_in_dimension)
413
+ ):
414
+ num_simplices = len(vertex_array)
415
+ if verbose:
416
+ print(
417
+ f"""
418
+ Inserting {num_simplices} simplices of dimension {dim}
419
+ ({num_simplices * len(ks)} birth values)...
420
+ """
421
+ )
422
+ max_knn_distances = np.max(knn_distances[vertex_array], axis=1)
423
+ critical_radii = np.maximum(alphas[:, None], beta * max_knn_distances)
424
+ filtrations = np.stack(
425
+ (
426
+ critical_radii,
427
+ (ks[-1] - ks if positive_degree else -ks)
428
+ * np.ones_like(critical_radii),
429
+ ),
430
+ axis=-1,
431
+ )
432
+ simplex_tree_multi.insert_batch(vertex_array.T, filtrations)
433
+
434
+ if verbose:
435
+ print("Done computing the Delaunay Core Bifiltration.")
436
+
437
+ return simplex_tree_multi
438
+
439
+
440
+ def RhomboidBifiltration(
441
+ x,
442
+ k_max: int,
443
+ degree: int,
444
+ verbose: bool = False,
445
+ ):
446
+ """
447
+ Rhomboid Tiling bifiltration.
448
+ This (1-critical) bifiltration is quasi-isomorphic to the (multi-critical) multicover bifiltration.
449
+ From [Computing the Multicover Bifiltration](https://doi.org/10.1007/s00454-022-00476-8), whose code
450
+ can be found here: https://github.com/geoo89/rhomboidtiling
451
+
452
+ Parameters
453
+ - x: 2d or 3d point cloud, of shape `(num_points,dimension)`.
454
+ - k_max(int): maximum number of cover to consider
455
+ - degree: dimension to consider
456
+ - verbose:bool
457
+ """
458
+ from multipers.io import _rhomboid_tiling_to_slicer
459
+ from multipers import Slicer
460
+
461
+ api = api_from_tensor(x)
462
+ if api.has_grad(x):
463
+ from warnings import warn
464
+
465
+ warn(
466
+ "Found a gradient in input, which cannot be processed by RhomboidBifiltration."
467
+ )
468
+ x = api.asnumpy(x)
469
+ if x.ndim not in (2, 3):
470
+ raise ValueError("Only 2-3D dimensional point cloud are supported.")
471
+ out = Slicer()
472
+ _rhomboid_tiling_to_slicer(
473
+ slicer=out,
474
+ point_cloud=x,
475
+ k_max=k_max,
476
+ verbose=verbose,
477
+ degree=degree,
478
+ )
479
+
480
+ return out