multipers 2.2.3__cp310-cp310-win_amd64.whl → 2.3.0__cp310-cp310-win_amd64.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.

Potentially problematic release.


This version of multipers might be problematic. Click here for more details.

Files changed (182) hide show
  1. multipers/__init__.py +33 -31
  2. multipers/_signed_measure_meta.py +430 -430
  3. multipers/_slicer_meta.py +211 -212
  4. multipers/data/MOL2.py +458 -458
  5. multipers/data/UCR.py +18 -18
  6. multipers/data/graphs.py +466 -466
  7. multipers/data/immuno_regions.py +27 -27
  8. multipers/data/pytorch2simplextree.py +90 -90
  9. multipers/data/shape3d.py +101 -101
  10. multipers/data/synthetic.py +113 -111
  11. multipers/distances.py +198 -198
  12. multipers/filtration_conversions.pxd.tp +84 -84
  13. multipers/filtrations/__init__.py +18 -0
  14. multipers/filtrations/filtrations.py +289 -0
  15. multipers/filtrations.pxd +224 -224
  16. multipers/function_rips.cp310-win_amd64.pyd +0 -0
  17. multipers/function_rips.pyx +105 -105
  18. multipers/grids.cp310-win_amd64.pyd +0 -0
  19. multipers/grids.pyx +350 -350
  20. multipers/gudhi/Persistence_slices_interface.h +132 -132
  21. multipers/gudhi/Simplex_tree_interface.h +239 -245
  22. multipers/gudhi/Simplex_tree_multi_interface.h +516 -561
  23. multipers/gudhi/cubical_to_boundary.h +59 -59
  24. multipers/gudhi/gudhi/Bitmap_cubical_complex.h +450 -450
  25. multipers/gudhi/gudhi/Bitmap_cubical_complex_base.h +1070 -1070
  26. multipers/gudhi/gudhi/Bitmap_cubical_complex_periodic_boundary_conditions_base.h +579 -579
  27. multipers/gudhi/gudhi/Debug_utils.h +45 -45
  28. multipers/gudhi/gudhi/Fields/Multi_field.h +484 -484
  29. multipers/gudhi/gudhi/Fields/Multi_field_operators.h +455 -455
  30. multipers/gudhi/gudhi/Fields/Multi_field_shared.h +450 -450
  31. multipers/gudhi/gudhi/Fields/Multi_field_small.h +531 -531
  32. multipers/gudhi/gudhi/Fields/Multi_field_small_operators.h +507 -507
  33. multipers/gudhi/gudhi/Fields/Multi_field_small_shared.h +531 -531
  34. multipers/gudhi/gudhi/Fields/Z2_field.h +355 -355
  35. multipers/gudhi/gudhi/Fields/Z2_field_operators.h +376 -376
  36. multipers/gudhi/gudhi/Fields/Zp_field.h +420 -420
  37. multipers/gudhi/gudhi/Fields/Zp_field_operators.h +400 -400
  38. multipers/gudhi/gudhi/Fields/Zp_field_shared.h +418 -418
  39. multipers/gudhi/gudhi/Flag_complex_edge_collapser.h +337 -337
  40. multipers/gudhi/gudhi/Matrix.h +2107 -2107
  41. multipers/gudhi/gudhi/Multi_critical_filtration.h +1038 -1038
  42. multipers/gudhi/gudhi/Multi_persistence/Box.h +171 -171
  43. multipers/gudhi/gudhi/Multi_persistence/Line.h +282 -282
  44. multipers/gudhi/gudhi/Off_reader.h +173 -173
  45. multipers/gudhi/gudhi/One_critical_filtration.h +1432 -1431
  46. multipers/gudhi/gudhi/Persistence_matrix/Base_matrix.h +769 -769
  47. multipers/gudhi/gudhi/Persistence_matrix/Base_matrix_with_column_compression.h +686 -686
  48. multipers/gudhi/gudhi/Persistence_matrix/Boundary_matrix.h +842 -842
  49. multipers/gudhi/gudhi/Persistence_matrix/Chain_matrix.h +1350 -1350
  50. multipers/gudhi/gudhi/Persistence_matrix/Id_to_index_overlay.h +1105 -1105
  51. multipers/gudhi/gudhi/Persistence_matrix/Position_to_index_overlay.h +859 -859
  52. multipers/gudhi/gudhi/Persistence_matrix/RU_matrix.h +910 -910
  53. multipers/gudhi/gudhi/Persistence_matrix/allocators/entry_constructors.h +139 -139
  54. multipers/gudhi/gudhi/Persistence_matrix/base_pairing.h +230 -230
  55. multipers/gudhi/gudhi/Persistence_matrix/base_swap.h +211 -211
  56. multipers/gudhi/gudhi/Persistence_matrix/boundary_cell_position_to_id_mapper.h +60 -60
  57. multipers/gudhi/gudhi/Persistence_matrix/boundary_face_position_to_id_mapper.h +60 -60
  58. multipers/gudhi/gudhi/Persistence_matrix/chain_pairing.h +136 -136
  59. multipers/gudhi/gudhi/Persistence_matrix/chain_rep_cycles.h +190 -190
  60. multipers/gudhi/gudhi/Persistence_matrix/chain_vine_swap.h +616 -616
  61. multipers/gudhi/gudhi/Persistence_matrix/columns/chain_column_extra_properties.h +150 -150
  62. multipers/gudhi/gudhi/Persistence_matrix/columns/column_dimension_holder.h +106 -106
  63. multipers/gudhi/gudhi/Persistence_matrix/columns/column_utilities.h +219 -219
  64. multipers/gudhi/gudhi/Persistence_matrix/columns/entry_types.h +327 -327
  65. multipers/gudhi/gudhi/Persistence_matrix/columns/heap_column.h +1140 -1140
  66. multipers/gudhi/gudhi/Persistence_matrix/columns/intrusive_list_column.h +934 -934
  67. multipers/gudhi/gudhi/Persistence_matrix/columns/intrusive_set_column.h +934 -934
  68. multipers/gudhi/gudhi/Persistence_matrix/columns/list_column.h +980 -980
  69. multipers/gudhi/gudhi/Persistence_matrix/columns/naive_vector_column.h +1092 -1092
  70. multipers/gudhi/gudhi/Persistence_matrix/columns/row_access.h +192 -192
  71. multipers/gudhi/gudhi/Persistence_matrix/columns/set_column.h +921 -921
  72. multipers/gudhi/gudhi/Persistence_matrix/columns/small_vector_column.h +1093 -1093
  73. multipers/gudhi/gudhi/Persistence_matrix/columns/unordered_set_column.h +1012 -1012
  74. multipers/gudhi/gudhi/Persistence_matrix/columns/vector_column.h +1244 -1244
  75. multipers/gudhi/gudhi/Persistence_matrix/matrix_dimension_holders.h +186 -186
  76. multipers/gudhi/gudhi/Persistence_matrix/matrix_row_access.h +164 -164
  77. multipers/gudhi/gudhi/Persistence_matrix/ru_pairing.h +156 -156
  78. multipers/gudhi/gudhi/Persistence_matrix/ru_rep_cycles.h +376 -376
  79. multipers/gudhi/gudhi/Persistence_matrix/ru_vine_swap.h +540 -540
  80. multipers/gudhi/gudhi/Persistent_cohomology/Field_Zp.h +118 -118
  81. multipers/gudhi/gudhi/Persistent_cohomology/Multi_field.h +173 -173
  82. multipers/gudhi/gudhi/Persistent_cohomology/Persistent_cohomology_column.h +128 -128
  83. multipers/gudhi/gudhi/Persistent_cohomology.h +745 -745
  84. multipers/gudhi/gudhi/Points_off_io.h +171 -171
  85. multipers/gudhi/gudhi/Simple_object_pool.h +69 -69
  86. multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_iterators.h +463 -463
  87. multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_node_explicit_storage.h +83 -83
  88. multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_siblings.h +106 -106
  89. multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_star_simplex_iterators.h +277 -277
  90. multipers/gudhi/gudhi/Simplex_tree/hooks_simplex_base.h +62 -62
  91. multipers/gudhi/gudhi/Simplex_tree/indexing_tag.h +27 -27
  92. multipers/gudhi/gudhi/Simplex_tree/serialization_utils.h +62 -62
  93. multipers/gudhi/gudhi/Simplex_tree/simplex_tree_options.h +157 -157
  94. multipers/gudhi/gudhi/Simplex_tree.h +2794 -2794
  95. multipers/gudhi/gudhi/Simplex_tree_multi.h +152 -163
  96. multipers/gudhi/gudhi/distance_functions.h +62 -62
  97. multipers/gudhi/gudhi/graph_simplicial_complex.h +104 -104
  98. multipers/gudhi/gudhi/persistence_interval.h +253 -253
  99. multipers/gudhi/gudhi/persistence_matrix_options.h +170 -170
  100. multipers/gudhi/gudhi/reader_utils.h +367 -367
  101. multipers/gudhi/mma_interface_coh.h +256 -255
  102. multipers/gudhi/mma_interface_h0.h +223 -231
  103. multipers/gudhi/mma_interface_matrix.h +284 -282
  104. multipers/gudhi/naive_merge_tree.h +536 -575
  105. multipers/gudhi/scc_io.h +310 -289
  106. multipers/gudhi/truc.h +890 -888
  107. multipers/io.cp310-win_amd64.pyd +0 -0
  108. multipers/io.pyx +711 -711
  109. multipers/ml/accuracies.py +90 -90
  110. multipers/ml/convolutions.py +520 -520
  111. multipers/ml/invariants_with_persistable.py +79 -79
  112. multipers/ml/kernels.py +176 -176
  113. multipers/ml/mma.py +713 -714
  114. multipers/ml/one.py +472 -472
  115. multipers/ml/point_clouds.py +352 -346
  116. multipers/ml/signed_measures.py +1589 -1589
  117. multipers/ml/sliced_wasserstein.py +461 -461
  118. multipers/ml/tools.py +113 -113
  119. multipers/mma_structures.cp310-win_amd64.pyd +0 -0
  120. multipers/mma_structures.pxd +127 -127
  121. multipers/mma_structures.pyx +4 -4
  122. multipers/mma_structures.pyx.tp +1085 -1085
  123. multipers/multi_parameter_rank_invariant/diff_helpers.h +84 -93
  124. multipers/multi_parameter_rank_invariant/euler_characteristic.h +97 -97
  125. multipers/multi_parameter_rank_invariant/function_rips.h +322 -322
  126. multipers/multi_parameter_rank_invariant/hilbert_function.h +769 -769
  127. multipers/multi_parameter_rank_invariant/persistence_slices.h +148 -148
  128. multipers/multi_parameter_rank_invariant/rank_invariant.h +369 -369
  129. multipers/multiparameter_edge_collapse.py +41 -41
  130. multipers/multiparameter_module_approximation/approximation.h +2296 -2295
  131. multipers/multiparameter_module_approximation/combinatory.h +129 -129
  132. multipers/multiparameter_module_approximation/debug.h +107 -107
  133. multipers/multiparameter_module_approximation/format_python-cpp.h +286 -286
  134. multipers/multiparameter_module_approximation/heap_column.h +238 -238
  135. multipers/multiparameter_module_approximation/images.h +79 -79
  136. multipers/multiparameter_module_approximation/list_column.h +174 -174
  137. multipers/multiparameter_module_approximation/list_column_2.h +232 -232
  138. multipers/multiparameter_module_approximation/ru_matrix.h +347 -347
  139. multipers/multiparameter_module_approximation/set_column.h +135 -135
  140. multipers/multiparameter_module_approximation/structure_higher_dim_barcode.h +36 -36
  141. multipers/multiparameter_module_approximation/unordered_set_column.h +166 -166
  142. multipers/multiparameter_module_approximation/utilities.h +403 -419
  143. multipers/multiparameter_module_approximation/vector_column.h +223 -223
  144. multipers/multiparameter_module_approximation/vector_matrix.h +331 -331
  145. multipers/multiparameter_module_approximation/vineyards.h +464 -464
  146. multipers/multiparameter_module_approximation/vineyards_trajectories.h +649 -649
  147. multipers/multiparameter_module_approximation.cp310-win_amd64.pyd +0 -0
  148. multipers/multiparameter_module_approximation.pyx +216 -217
  149. multipers/pickle.py +90 -53
  150. multipers/plots.py +342 -334
  151. multipers/point_measure.cp310-win_amd64.pyd +0 -0
  152. multipers/point_measure.pyx +322 -320
  153. multipers/simplex_tree_multi.cp310-win_amd64.pyd +0 -0
  154. multipers/simplex_tree_multi.pxd +133 -133
  155. multipers/simplex_tree_multi.pyx +18 -15
  156. multipers/simplex_tree_multi.pyx.tp +1939 -1935
  157. multipers/slicer.cp310-win_amd64.pyd +0 -0
  158. multipers/slicer.pxd +81 -20
  159. multipers/slicer.pxd.tp +215 -214
  160. multipers/slicer.pyx +1091 -308
  161. multipers/slicer.pyx.tp +924 -914
  162. multipers/tensor/tensor.h +672 -672
  163. multipers/tensor.pxd +13 -13
  164. multipers/test.pyx +44 -44
  165. multipers/tests/__init__.py +57 -57
  166. multipers/torch/diff_grids.py +217 -217
  167. multipers/torch/rips_density.py +310 -304
  168. {multipers-2.2.3.dist-info → multipers-2.3.0.dist-info}/LICENSE +21 -21
  169. {multipers-2.2.3.dist-info → multipers-2.3.0.dist-info}/METADATA +21 -11
  170. multipers-2.3.0.dist-info/RECORD +182 -0
  171. multipers/tests/test_diff_helper.py +0 -73
  172. multipers/tests/test_hilbert_function.py +0 -82
  173. multipers/tests/test_mma.py +0 -83
  174. multipers/tests/test_point_clouds.py +0 -49
  175. multipers/tests/test_python-cpp_conversion.py +0 -82
  176. multipers/tests/test_signed_betti.py +0 -181
  177. multipers/tests/test_signed_measure.py +0 -89
  178. multipers/tests/test_simplextreemulti.py +0 -221
  179. multipers/tests/test_slicer.py +0 -221
  180. multipers-2.2.3.dist-info/RECORD +0 -189
  181. {multipers-2.2.3.dist-info → multipers-2.3.0.dist-info}/WHEEL +0 -0
  182. {multipers-2.2.3.dist-info → multipers-2.3.0.dist-info}/top_level.txt +0 -0
multipers/slicer.pyx.tp CHANGED
@@ -1,914 +1,924 @@
1
- {{py:
2
-
3
- """
4
- Vine and non-vine slicers.
5
- both type have the same interface, defined the slicer.pyx file
6
- """
7
-
8
-
9
- import pickle
10
-
11
- with open("build/tmp/_slicer_names.pkl", "rb") as f:
12
- slicers=pickle.load(f)
13
-
14
-
15
- }}
16
-
17
- from multipers.simplex_tree_multi import SimplexTreeMulti, SimplexTreeMulti_type
18
- import multipers
19
- from typing import Optional,Literal
20
- import multipers.io as mio
21
- import multipers.grids as mpg
22
- import threading
23
- import os
24
- from joblib import Parallel, delayed
25
-
26
- from multipers.slicer cimport *
27
- from multipers.filtrations cimport *
28
- from multipers.filtration_conversions cimport *
29
- ## TODO: these two are not needed, remove that by updating rank code.
30
- from multipers.point_measure import sparsify, rank_decomposition_by_rectangles
31
-
32
- import numpy as np
33
- cimport cython
34
- from libcpp.string cimport string
35
- # python_value_type = np.float32
36
- from typing import Union
37
- from cython.operator cimport dereference
38
-
39
- ## WARNING : This is repeated in the pxd file ...
40
- python_indices_type=np.int32
41
- python_tensor_dtype = np.int32
42
-
43
- global available_slicers
44
- available_slicers = tuple((
45
- {{for D in slicers}}
46
- {{D['PYTHON_TYPE']}},
47
- {{endfor}}
48
- ))
49
-
50
- global available_columns
51
- available_columns = set((
52
- {{for D in slicers}}
53
- "{{D['COLUMN_TYPE']}}",
54
- {{endfor}}
55
- ))
56
-
57
- global available_dtype
58
- available_dtype = set([
59
- {{for D in slicers}}
60
- "{{D['PY_VALUE_TYPE']}}",
61
- {{endfor}}
62
- ])
63
-
64
-
65
- global available_pers_backend
66
- available_pers_backend = set([
67
- {{for D in slicers}}
68
- "{{D['PERS_BACKEND_TYPE']}}",
69
- {{endfor}}
70
- ])
71
-
72
-
73
-
74
- global column_type
75
- _column_type = Literal[
76
- {{for D in slicers}}
77
- "{{D['COLUMN_TYPE']}}",
78
- {{endfor}}
79
- ]
80
-
81
- global _slicers_type
82
- Slicer_type = Union[
83
- {{for D in slicers}}
84
- {{D['PYTHON_TYPE']}},
85
- {{endfor}}
86
- ]
87
-
88
- global _valid_dtypes
89
- _valid_dtype = Union[
90
- {{for D in slicers}}
91
- {{D['PY_VALUE_TYPE']}},
92
- {{endfor}}
93
- ]
94
-
95
-
96
- global _valid_pers_backend
97
- _valid_pers_backend = Literal[
98
- {{for D in slicers}}
99
- "{{D['PERS_BACKEND_TYPE']}}",
100
- {{endfor}}
101
- ]
102
-
103
- {{for D in slicers}}
104
-
105
- #------------------------------------------------------------------------------
106
- cdef class {{D['PYTHON_TYPE']}}:
107
- cdef {{D['C_TEMPLATE_TYPE']}} truc
108
- cdef public vector[vector[double]] filtration_grid
109
- cdef public int minpres_degree ## TODO : maybe change directly the degree in the minpres ?
110
-
111
- def __repr__(self):
112
- return f"slicer[backend={self.pers_backend},dtype={np.dtype(self.dtype).name},num_param={self.num_parameters},vineyard={self.is_vine},kcritical={self.is_kcritical},is_squeezed={self.is_squeezed},is_minpres={self.is_minpres},max_dim={self.dimension}]"
113
-
114
- @property
115
- def is_squeezed(self)->bool:
116
- return self.filtration_grid.size() > 0 and self.filtration_grid[0].size() > 0
117
- @property
118
- def is_minpres(self)->bool:
119
- return self.minpres_degree>=0
120
- @staticmethod
121
- def _inf_value():
122
- return np.asarray(np.inf,dtype={{D['PY_VALUE_TYPE']}}) if issubclass({{D['PY_VALUE_TYPE']}},np.floating) else np.iinfo({{D['PY_VALUE_TYPE']}}).max
123
-
124
- def get_ptr(self):
125
- """
126
- Returns a pointer to the underlying C++ slicer.
127
- """
128
- return <intptr_t>(&self.truc)
129
- def _from_ptr(self, intptr_t slicer_ptr):
130
- self.truc = dereference(<{{D['C_TEMPLATE_TYPE']}}*>(slicer_ptr))
131
- return self
132
-
133
- {{if D['IS_SIMPLICIAL']}}
134
- def __init__(self, st=None):
135
- """
136
- Constructs a slicer from a simplex tree.
137
- """
138
- pass
139
- def __cinit__(self, st=None):
140
- if st is None:
141
- return
142
- cdef intptr_t ptr = st.thisptr
143
- cdef Simplex_tree_multi_interface[{{D['FILTRATION_TYPE']}},{{D['C_VALUE_TYPE']}}]* st_ptr = <Simplex_tree_multi_interface[{{D['FILTRATION_TYPE']}},{{D['C_VALUE_TYPE']}}]*>(ptr)
144
- self.truc = {{D['C_TEMPLATE_TYPE']}}(st_ptr)
145
- self.minpres_degree = -1
146
- {{elif D['IS_KCRITICAL']}}
147
- def __init__(self, generator_maps=[], generator_dimensions=[], filtration_values=[]):
148
- """
149
- Constructs a slicer from
150
- - scc-like blocks
151
- or
152
- - generator maps (Iterable of list of ints)
153
- - generator dimensions (Iterable of int)
154
- - filtration values (Iterable of filtration values)
155
- """
156
- pass
157
- def __cinit__(self, generator_maps=[], generator_dimensions=[], filtration_values=[]):
158
- """
159
- Cython constructor
160
- """
161
- if len(generator_maps)>0 and len(generator_dimensions) == 0 and len(filtration_values) == 0:
162
- from multipers._slicer_meta import _blocks2boundary_dimension_grades
163
- generator_maps, generator_dimensions, filtration_values = _blocks2boundary_dimension_grades(
164
- generator_maps,
165
- inplace=False,
166
- )
167
- cdef uint32_t num_generators = len(generator_maps)
168
- cdef vector[vector[uint32_t]] c_generator_maps
169
- cdef vector[Multi_critical_filtration[{{D['C_VALUE_TYPE']}}]] c_filtration_values
170
- for stuff in generator_maps:
171
- c_generator_maps.push_back(<vector[uint32_t]>(stuff))
172
- cdef Multi_critical_filtration[{{D['C_VALUE_TYPE']}}] cf
173
- cdef One_critical_filtration[{{D['C_VALUE_TYPE']}}] inf
174
- inf[0] = -inf[0]
175
- cdef {{D['C_VALUE_TYPE']}}[:,:] F_view
176
- for F in filtration_values:
177
- cf.push_to_least_common_upper_bound(inf)
178
- F_view = np.asarray(F, dtype = {{D['PY_VALUE_TYPE']}} )
179
- for i in range(F_view.shape[0]):
180
- cf.add_generator(_py21c_{{D['SHORT_VALUE_TYPE']}}(F_view[i]))
181
- c_filtration_values.push_back(cf)
182
- cdef vector[int] c_generator_dimensions = generator_dimensions
183
- assert num_generators == c_generator_maps.size() == c_filtration_values.size(), "Invalid input, shape do not coincide."
184
- self.truc = {{D['C_TEMPLATE_TYPE']}}(c_generator_maps,c_generator_dimensions, c_filtration_values)
185
- self.minpres_degree = -1
186
- {{else}}
187
- def __init__(self, generator_maps=[], generator_dimensions=[], filtration_values=[]):
188
- """
189
- Constructs a slicer from
190
- - generator maps (Iterable of list of ints)
191
- - generator dimensions (Iterable of int)
192
- - filtration values (Iterable of filtration values)
193
- """
194
- pass
195
- @cython.boundscheck(False)
196
- @cython.wraparound(False)
197
- def __cinit__(self, generator_maps=[], generator_dimensions=[], filtration_values=[]):
198
- """
199
- Cython constructor
200
- """
201
- cdef uint32_t num_generators = len(generator_maps)
202
- filtration_values = np.asarray(filtration_values, dtype = {{D['PY_VALUE_TYPE']}} )
203
- assert len(filtration_values) == num_generators, f"Invalid input, shape do not coicide. Got sizes {num_generators,len(generator_dimensions),len(filtration_values)}."
204
- cdef vector[vector[uint32_t]] c_generator_maps
205
- cdef vector[One_critical_filtration[{{D['C_VALUE_TYPE']}}]] c_filtration_values
206
-
207
- c_generator_maps.resize(num_generators)
208
- c_filtration_values.resize(num_generators)
209
- for i in range(num_generators):
210
- c_generator_maps[i] = <vector[uint32_t]>(generator_maps[i])
211
- c_filtration_values[i] = _py21c_{{D['SHORT_VALUE_TYPE']}}(filtration_values[i])
212
- cdef vector[int] c_generator_dimensions = generator_dimensions
213
-
214
- assert num_generators == c_generator_maps.size() == c_filtration_values.size() == c_generator_dimensions.size(), "Invalid input, shape do not coincide."
215
- self.truc = {{D['C_TEMPLATE_TYPE']}}(c_generator_maps,c_generator_dimensions, c_filtration_values)
216
- self.minpres_degree = -1
217
- {{endif}}
218
-
219
- def copy(self)->{{D['PYTHON_TYPE']}}:
220
- """
221
- Returns a copy of the slicer.
222
- """
223
- copy_ = {{D['PYTHON_TYPE']}}()
224
- copy_.truc = self.truc
225
- copy_.minpres_degree = self.minpres_degree
226
- copy_.filtration_grid = self.filtration_grid
227
- return copy_
228
- def get_barcode(self):
229
- """
230
- Returns the current barcode.
231
- """
232
- return self.truc.get_barcode()
233
- def push_to_line(self, basepoint, direction=None)->{{D['PYTHON_TYPE']}}:
234
- """
235
- Pushes the current slicer to the line defined by a basepoint and an optional direction.
236
- If the direction is not provided, it is assumed to be diagonal.
237
- """
238
- basepoint = np.asarray(basepoint, dtype = {{D['PY_VALUE_TYPE']}})
239
- cdef Line[{{D['C_VALUE_TYPE']}}] line
240
- if direction is None:
241
- line = Line[{{D['C_VALUE_TYPE']}}](_py21c_{{D['SHORT_VALUE_TYPE']}}(basepoint))
242
- else:
243
- direction = np.asarray(direction, dtype = {{D['PY_VALUE_TYPE']}})
244
- line = Line[{{D['C_VALUE_TYPE']}}](_py21c_{{D['SHORT_VALUE_TYPE']}}(basepoint),_py21c_{{D['SHORT_VALUE_TYPE']}}(direction))
245
- self.truc.push_to(line)
246
- return self
247
-
248
- @staticmethod
249
- cdef _threshold_bcs(vector[vector[pair[{{D['C_VALUE_TYPE']}}, {{D['C_VALUE_TYPE']}}]]] bcs):
250
- return tuple(np.fromiter((a for a in stuff if a.first < {{D['PYTHON_TYPE']}}._inf_value()), dtype=np.dtype(({{D['PY_VALUE_TYPE']}},2))) for stuff in bcs)
251
- @staticmethod
252
- def _bc_to_full(bcs, basepoint, direction=None):
253
- # i, (b sv d), coords
254
- basepoint = np.asarray(basepoint)[None,None,:]
255
- direction = 1 if direction is None else np.asarray(direction)[None,None,:]
256
- return tuple(bc[:,:,None]*direction + basepoint for bc in bcs)
257
-
258
- def persistence_on_line(self,basepoint,direction=None, bool keep_inf=True, bool full=False):
259
- """
260
- Computes the persistence on a line L defined by
261
- - a basepoint (num_parameters,) array
262
- - an optional direction (num_parameters,) array
263
-
264
- Warning: This is not parallelizable. Use `persitence_on_lines`.
265
- """
266
- self.push_to_line(basepoint,direction)
267
- self.truc.compute_persistence()
268
- if keep_inf:
269
- bcs = tuple(np.asarray(stuff, dtype = {{D['PY_VALUE_TYPE']}}) for stuff in self.truc.get_barcode())
270
- else:
271
- bcs = {{D['PYTHON_TYPE']}}._threshold_bcs(self.truc.get_barcode())
272
-
273
- if full:
274
- bcs = {{D['PYTHON_TYPE']}}._bc_to_full(bcs, basepoint, direction)
275
- return bcs
276
-
277
- def persistence_on_lines(self, basepoints=None, directions=None, bool keep_inf=True, bool full=False):
278
- """
279
- Same as `persistence_on_line`, but with vineyards operation between
280
- lines if `self.is_vine`, and in parallel otherwise.
281
- """
282
- cdef vector[vector[{{D['C_VALUE_TYPE']}}]] c_basepoints
283
- cdef vector[pair[vector[{{D['C_VALUE_TYPE']}}], vector[{{D['C_VALUE_TYPE']}}]]] c_truc
284
- cdef vector[vector[vector[pair[{{D['C_VALUE_TYPE']}}, {{D['C_VALUE_TYPE']}}]]]] c_out
285
- if directions is None:
286
- c_basepoints = basepoints
287
- with nogil:
288
- c_out = self.truc.persistence_on_lines(c_basepoints)
289
- else:
290
- c_truc = zip(basepoints,directions)
291
- with nogil:
292
- c_out = self.truc.persistence_on_lines(c_truc)
293
- cdef int num_bc = c_basepoints.size()
294
-
295
- if keep_inf:
296
- out = tuple(tuple(np.asarray(y, dtype = {{D['PY_VALUE_TYPE']}}) for y in x) for x in c_out)
297
- else:
298
- out = tuple({{D['PYTHON_TYPE']}}._threshold_bcs(x) for x in c_out)
299
-
300
- if full:
301
- _dirs = [None]*len(basepoints) if directions is None else directions
302
- out = tuple({{D['PYTHON_TYPE']}}._bc_to_full(bcs, bp, dir) for bcs, bp, dir in zip(out,basepoints,_dirs))
303
- return out
304
-
305
-
306
- def __getstate__(self):
307
- return (
308
- self.get_boundaries(),
309
- self.get_dimensions(),
310
- self.get_filtrations(),
311
- tuple(np.array(f) for f in self.filtration_grid),
312
- self.minpres_degree,
313
- )
314
- def __setstate__(self, tuple dump):
315
- B, D, F, filtration_grid, minpres_degree = dump
316
- copy = {{D['PYTHON_TYPE']}}(B,D,F)
317
- self.truc = copy.truc
318
- self.minpres_degree= minpres_degree
319
- self.filtration_grid=filtration_grid
320
-
321
- def __eq__(self, other):
322
- ## True if they rpz the same complex (no reordering allowed yet),
323
- # i.e., ignores minpres, squeeze
324
- if other.is_squeezed:
325
- return self == other.unsqueeze()
326
- if self.is_squeezed:
327
- return self.unsqueeze() == other
328
- return (
329
- np.array_equal(self.get_dimensions(), other.get_dimensions())
330
- and
331
- self.get_boundaries() == other.get_boundaries()
332
- and
333
- ## Kcritical are sorted + filtrationvalues is a dump.
334
- # for non kcritical there is an unnecessary copy though
335
- np.array_equal(self.get_filtrations_values(), other.get_filtrations_values())
336
- )
337
-
338
-
339
-
340
- def compute_persistence(self,one_filtration=None, bool ignore_infinite_filtration_values = True)->{{D['PYTHON_TYPE']}}:
341
- """
342
- Computes the current persistence, or the persistence
343
- given by the filtration one_filtration (num_generators,).
344
- """
345
- if one_filtration is not None:
346
- self.truc.set_one_filtration(one_filtration)
347
- # TODO: Later
348
- # if len(degrees)>0:
349
- # self.truc.compute_persistence(degrees)
350
- # else:
351
- # self.truc.compute_persistence()
352
- self.truc.compute_persistence(ignore_infinite_filtration_values)
353
- return self
354
- # return self.truc.get_barcode()
355
- def get_barcode(self):
356
- """
357
- Returns the barcode of the current 1d-persistence.
358
- """
359
- return self.truc.get_barcode()
360
- def sliced_filtration(self,basepoint, direction=None):
361
- """
362
- Computes the filtration on a line L defined by
363
- - a basepoint (num_parameters,) array
364
- - an optional direction (num_parameters,) array
365
- """
366
- self.push_to_line(basepoint,direction)
367
- return np.asarray(self.truc.get_one_filtration())
368
- def __len__(self):
369
- return self.truc.num_generators()
370
- @property
371
- def num_generators(self):
372
- return self.truc.num_generators()
373
- @property
374
- def num_parameters(self):
375
- return self.truc.num_parameters()
376
- @property
377
- def info(self):
378
- print(self.truc.to_str().decode())
379
- def filtration_bounds(self) -> np.ndarray:
380
- """
381
- Computes the bounding box of the current multifiltration.
382
- """
383
- cdef pair[One_critical_filtration[{{D['C_VALUE_TYPE']}}],One_critical_filtration[{{D['C_VALUE_TYPE']}}]] box = self.truc.get_bounding_box()
384
- cdef cnp.ndarray[{{D['C_VALUE_TYPE']}}, ndim=1] a = _ff21cview_{{D['SHORT_VALUE_TYPE']}}(&box.first)
385
- cdef cnp.ndarray[{{D['C_VALUE_TYPE']}}, ndim=1] b = _ff21cview_{{D['SHORT_VALUE_TYPE']}}(&box.second)
386
- return np.asarray([a,b])
387
- def get_filtrations_values(self)->np.ndarray:
388
- """
389
- Returns the current filtration values of the slicer.
390
- """
391
- cdef vector[One_critical_filtration[{{D['C_VALUE_TYPE']}}]] v = self.truc.get_filtration_values()
392
- out = _vff21cview_{{D['SHORT_VALUE_TYPE']}}(v, copy=True, duplicate=self.num_parameters)
393
- return np.asarray(out)
394
- def get_filtration_grid(self,grid_strategy:str="exact", **infer_grid_kwargs):
395
- return mpg.compute_grid(
396
- self.get_filtrations_values().T,
397
- strategy=grid_strategy,
398
- **infer_grid_kwargs,
399
- )
400
- def get_filtrations(self):
401
- """
402
- Returns a view of the filtration values, as a list of numpy arrays.
403
- """
404
- {{if D['IS_KCRITICAL']}}
405
- return _vff2kcview_{{D['SHORT_VALUE_TYPE']}}(self.truc.get_filtrations(), copy=False, duplicate=self.num_parameters)
406
- {{else}}
407
- return _vff21cview_{{D['SHORT_VALUE_TYPE']}}(self.truc.get_filtrations(), copy=False, duplicate=self.num_parameters)
408
- {{endif}}
409
-
410
- def get_dimensions(self)-> np.ndarray:
411
- """
412
- Returns the ordered dimensions of the generators.
413
- """
414
- return np.asarray(self.truc.get_dimensions())
415
- @property
416
- def dimension(self)-> int:
417
- """
418
- Returns the maximum dimension of the complex.
419
- """
420
- return self.get_dimensions()[-1] if len(self)>0 else -np.inf
421
- def prune_above_dimension(self,int max_dimension)->{{D['PYTHON_TYPE']}}:
422
- """
423
- Prunes the generators above a given dimension.
424
- """
425
- self.truc.prune_above_dimension(max_dimension)
426
- return self
427
- def get_boundaries(self)->tuple[tuple]:
428
- """
429
- Returns the boundaries of the generators.
430
- """
431
- return tuple(tuple(b) for b in self.truc.get_boundaries())
432
- def grid_squeeze(self, filtration_grid=None, grid_strategy="exact", resolution:Optional[int]=None, bool coordinates=True, bool inplace = False, bool force=False)->{{D['PYTHON_TYPE'][:-3]+"i32"}}|{{D['PYTHON_TYPE']}}:
433
- """
434
- Coarsen the filtration values on a grid. This is necessary to compute some invariants.
435
-
436
- If the filtration grid is not given, it is infered from filtration values,
437
- using the :func:`multipers.grids.compute_grid` function, whose args are
438
- - grid_strategy:str see `multipers.grids.available_strategies`. Defaults to exact.
439
- - resolution:int if strategy is not exact.
440
-
441
- - inplace:bool if true, does the operation inplace, i.e., doesn't return a copy.
442
- """
443
- if not force and self.is_squeezed:
444
- raise ValueError("The slicer seems to be already squeezed. Use force=True to resqueeze.")
445
- if filtration_grid is None:
446
- filtration_grid = mpg.compute_grid(
447
- self.get_filtrations_values().T,
448
- strategy=grid_strategy,
449
- resolution=resolution)
450
- cdef vector[vector[{{D['C_VALUE_TYPE']}}]] grid = filtration_grid
451
- if inplace or not coordinates:
452
- self.truc.coarsen_on_grid_inplace(grid, coordinates)
453
- self.filtration_grid = filtration_grid
454
- else:
455
- {{if D['COLUMN_TYPE'] is None}}
456
- raise ValueError("WIP")
457
- {{else}}
458
- out = {{D['PYTHON_TYPE'][:-3]+"i32"}}()
459
- out.truc = self.truc.coarsen_on_grid(grid)
460
- out.filtration_grid = filtration_grid
461
- out.minpres_degree = self.minpres_degree
462
- return out
463
- {{endif}}
464
- return self
465
- def minpres(self,
466
- int degree=-1,
467
- list[int] degrees=[],
468
- str backend:Literal["mpfree", "2pac"]="mpfree",
469
- str slicer_backend:Literal["matrix","clement","graph"]="matrix",
470
- bool vineyard={{D['IS_VINE']}},
471
- id :Optional[str] = None,
472
- dtype = {{D['PY_VALUE_TYPE']}},
473
- **minpres_kwargs
474
- )->Slicer_type:
475
- """
476
- Computes the minimal presentation of the slicer, and returns it as a new slicer.
477
- See :func:`multipers.slicer.minimal_presentation`.
478
- """
479
- new_slicer = minimal_presentation(self, degree=degree, degrees=degrees, backend=backend, slicer_backend=slicer_backend, vineyard=vineyard, id=id, **minpres_kwargs)
480
- return new_slicer
481
-
482
- @property
483
- def dtype(self)->type:
484
- return {{D['PY_VALUE_TYPE']}}
485
- @property
486
- def col_type(self)->str:
487
- return "{{D['COLUMN_TYPE']}}"
488
- @property
489
- def is_vine(self)->bool:
490
- return {{D['IS_VINE']}}
491
- @property
492
- def is_kcritical(self)->bool:
493
- return {{D['IS_KCRITICAL']}}
494
-
495
- @property
496
- def pers_backend(self)->str:
497
- return "{{D['PERS_BACKEND_TYPE']}}"
498
-
499
- {{if D['IS_VINE']}}
500
- def vine_update(self,basepoint,direction=None)->{{D['PYTHON_TYPE']}}:
501
- """
502
- Updates the barcode, on a line, using the vineyard algorithm.
503
- """
504
- self.push_to_line(basepoint,direction)
505
- self.truc.vineyard_update()
506
- return self
507
- def get_representative_cycles(self, bool update=True, bool detailed=False):
508
- """
509
- Returns the representative cycles of the current barcode.
510
- Recomputes the generators if update=True
511
- """
512
- return self.truc.get_representative_cycles(update, detailed)
513
- def get_permutation(self):
514
- """
515
- Returns the current generator permutation (w.r.t. vineyard).
516
- """
517
- return self.truc.get_current_order()
518
- {{endif}}
519
-
520
- {{if not D['IS_KCRITICAL']}}
521
- def _build_from_scc_file(self, path:os.PathLike, bool rivet_compatible = False, bool reverse = False, int shift_dimension = 0)->{{D['PYTHON_TYPE']}}:
522
- """
523
- Builds the slicer from the given scc file. Should be empty before, otherwise will be completely overwritten.
524
- """
525
- cdef string c_path = path.encode(encoding="utf-8")
526
- with nogil:
527
- self.truc.build_from_scc_file(c_path, rivet_compatible, reverse, shift_dimension)
528
- return self
529
-
530
- def to_scc(
531
- self,
532
- path:os.PathLike,
533
- int num_parameters = -1,
534
- int degree = 1,
535
- bool rivet_compatible = False,
536
- bool ignore_last_generators = False,
537
- bool strip_comments = False,
538
- bool reverse = False,
539
- bool unsqueeze = True,
540
- ):
541
- """
542
- Writes current slicer to a file in scc format.
543
- """
544
- cdef string c_path = path.encode(encoding="utf-8")
545
- if self.is_squeezed and unsqueeze:
546
- kwargs = locals()
547
- kwargs.pop("self",0)
548
- kwargs.pop("c_path",0)
549
- self.unsqueeze().to_scc(**kwargs)
550
- return
551
- with nogil:
552
- self.truc.write_to_scc_file(c_path, num_parameters, degree, rivet_compatible, ignore_last_generators, strip_comments, reverse)
553
- def unsqueeze(self, grid=None, dtype = np.float64):
554
- from multipers.grids import evaluate_in_grid
555
- from multipers import Slicer
556
- grid = tuple(np.asarray(f) for f in self.filtration_grid) if grid is None else grid
557
- new_filtrations = evaluate_in_grid(np.asarray(self.get_filtrations(), dtype=np.int32), grid)
558
- new_slicer = {{D['PYTHON_TYPE'][:-3]+"f64"}}(
559
- self.get_boundaries(),
560
- self.get_dimensions(),
561
- new_filtrations,
562
- )
563
- new_slicer.minpres_degree=self.minpres_degree
564
- return new_slicer
565
- {{endif}}
566
-
567
-
568
- {{endfor}}
569
-
570
- from libcpp.vector cimport vector
571
- from libcpp.set cimport set as cset
572
- cdef extern from "gudhi/cubical_to_boundary.h" namespace "":
573
- void _to_boundary(const vector[unsigned int]&, vector[vector[unsigned int]]&, vector[int]&) except + nogil
574
- void get_vertices(unsigned int, cset[unsigned int]&, const vector[vector[unsigned int]]&) nogil
575
-
576
-
577
- def from_bitmap(image, **slicer_kwargs):
578
- from multipers import Slicer
579
- image = np.asarray(image)
580
- slicer_kwargs["dtype"] = slicer_kwargs.get("dtype", image.dtype)
581
- _Slicer = Slicer(return_type_only=True, **slicer_kwargs)
582
- cdef vector[unsigned int] img_shape = image.shape[:-1]
583
- cdef unsigned int num_parameters = image.shape[-1]
584
- cdef vector[vector[unsigned int]] gen_maps
585
- cdef vector[int] gen_dims
586
-
587
- with nogil:
588
- _to_boundary(img_shape,gen_maps, gen_dims)
589
-
590
- cdef unsigned int num_gens = gen_dims.size()
591
- filtration_values = np.zeros(shape=(num_gens, num_parameters), dtype = np.double) - np.inf
592
- cdef double[:,:] F = filtration_values
593
- cdef double[:,:] c_img = image.reshape(-1,num_parameters)
594
- cdef cset[unsigned int] vertices
595
- with nogil:
596
- for i in range(num_gens):
597
- # with gil:
598
- # print(f"idx {i}:", end="")
599
- vertices.clear()
600
- get_vertices(i,vertices,gen_maps)
601
-
602
- # with gil:
603
- # print(f"v = {vertices}:", end="")
604
- for k in vertices:
605
- for j in range(num_parameters):
606
- F[i,j] = max(F[i,j], c_img[k,j])
607
-
608
- # with gil:
609
- # print(f"F = {np.asarray(F[i])}")
610
- slicer = _Slicer(gen_maps, gen_dims, filtration_values)
611
- return slicer
612
-
613
- def from_function_delaunay(
614
- points,
615
- grades,
616
- int degree=-1,
617
- backend: Optional[_valid_pers_backend]=None,
618
- vineyard:Optional[bool]=None,
619
- dtype=np.float64,
620
- bool verbose = False,
621
- bool clear = True,
622
- ):
623
- """
624
- Given points in $\mathbb R^n$ and function grades, compute the function-delaunay
625
- bifiltration as a in an scc format, and converts it into a slicer.
626
-
627
- points : (num_pts, n) float array
628
- grades : (num_pts,) float array
629
- degree (opt) : if given, computes a minimal presentation of this homological degree first
630
- backend : slicer backend, e.g. "matrix", "clement"
631
- vineyard : bool, use a vineyard-compatible backend
632
- """
633
- s = multipers.Slicer(None, backend=backend, vineyard=vineyard, dtype=dtype)
634
- mio.function_delaunay_presentation_to_slicer(s, points, grades, degree=degree, verbose=verbose,clear=clear)
635
- if degree >= 0:
636
- s.minpres_degree = degree
637
- return s
638
-
639
- def slicer2blocks(slicer, int degree = -1, bool reverse=True):
640
- """
641
- Convert any slicer to the block format a.k.a. scc format for python
642
- """
643
- dims = slicer.get_dimensions()
644
- num_empty_blocks_to_add = 1 if degree == -1 else dims.min()-degree +1
645
- _,counts = np.unique(dims, return_counts=True, )
646
- indices = np.concatenate([[0],counts], dtype=np.int32).cumsum()
647
- filtration_values = slicer.get_filtrations()
648
- filtration_values = [filtration_values[indices[i]:indices[i+1]] for i in range(len(indices)-1)]
649
- boundaries = slicer.get_boundaries()
650
- boundaries = [boundaries[indices[i]:indices[i+1]] for i in range(len(indices)-1)]
651
- shift = np.concatenate([[0], indices], dtype=np.int32)
652
- boundaries = [tuple(np.asarray(x-s, dtype=np.int32) for x in block) for s,block in zip(shift,boundaries)]
653
- blocks = [tuple((f,tuple(b))) for b,f in zip(boundaries,filtration_values)]
654
- blocks = ([(np.empty((0,)),[])]*num_empty_blocks_to_add) + blocks
655
- if reverse:
656
- blocks.reverse()
657
- return blocks
658
-
659
- def minimal_presentation(
660
- slicer,
661
- int degree = -1,
662
- degrees:Iterable[int]=[],
663
- str backend:Literal["mpfree", "2pac", ""]="mpfree",
664
- str slicer_backend:Literal["matrix","clement","graph"]="matrix",
665
- bool vineyard=True,
666
- id :Optional[str] =None,
667
- dtype:type|_valid_dtypes=None,
668
- int n_jobs = -1,
669
- bool force=False,
670
- **minpres_kwargs
671
- ):
672
- """
673
- Computes a minimal presentation of the multifiltered complex given by the slicer,
674
- and returns it as a slicer.
675
- Backends differents than `mpfree` are unstable.
676
- """
677
- if is_slicer(slicer) and slicer.is_minpres and not force:
678
- from warnings import warn
679
- warn(f"The slicer seems to be already reduced, from homology of degree {slicer.minpres_degree}.")
680
- return slicer
681
- mio._init_external_softwares(requires=[backend])
682
- if len(degrees)>0:
683
- def todo(int degree):
684
- return minimal_presentation(slicer, degree=degree, backend=backend, slicer_backend=slicer_backend, vineyard=vineyard, id=id, **minpres_kwargs)
685
- return tuple(
686
- Parallel(n_jobs=n_jobs, backend="threading")(delayed(todo)(d) for d in degrees)
687
- )
688
- # return tuple(minimal_presentation(slicer, degree=d, backend=backend, slicer_backend=slicer_backend, vineyard=vineyard, id=id, **minpres_kwargs) for d in degrees)
689
- assert degree>=0, f"Degree not provided."
690
- filtration_grid = slicer.filtration_grid if slicer.is_squeezed else None
691
- if id is None:
692
- id = str(threading.get_native_id())
693
- if dtype is None:
694
- dtype = slicer.dtype
695
- dimension = slicer.dimension - degree # latest = L-1, which is empty, -1 for degree 0, -2 for degree 1 etc.
696
- slicer.to_scc(path=mio.input_path+id, strip_comments=True, degree=degree-1)
697
- new_slicer = multipers.Slicer(None,backend=slicer_backend, vineyard=vineyard, dtype=dtype)
698
- if backend=="mpfree":
699
- shift_dimension=degree-1
700
- else:
701
- shift_dimension=degree
702
- mio.scc_reduce_from_str_to_slicer(path=mio.input_path+id, slicer=new_slicer, dimension=dimension, backend=backend, shift_dimension=shift_dimension, **minpres_kwargs)
703
- new_slicer.minpres_degree = degree
704
- if filtration_grid is not None:
705
- new_slicer.filtration_grid = filtration_grid
706
- return new_slicer
707
-
708
-
709
- def to_simplextree(s:Slicer_type, max_dim:int=-1) -> SimplexTreeMulti_type:
710
- """
711
- Turns a --simplicial-- slicer into a simplextree.
712
-
713
- Warning: Won't work for non-simplicial complexes,
714
- i.e., complexes $K$ not satisfying
715
- $\forall \sigma \in K,\, \mathrm{dim}(\sigma) = |\partial \sigma|-1$
716
- """
717
- dims = s.get_dimensions()
718
- assert np.all(dims[:-1] <= dims[1:]), "Dims is not sorted."
719
- idx = np.searchsorted(dims, np.unique(dims))
720
- idx = np.concatenate([idx, [dims.shape[0]]])
721
- if max_dim>=0:
722
- idx = idx[:max_dim+2]
723
-
724
- cdef vector[vector[int]] boundaries_ = s.get_boundaries()
725
- cdef int a
726
- cdef int b
727
- if len(idx)>2:
728
- a = idx[2]
729
- b = idx[-1]
730
- for i in range(a, b):
731
- boundaries_[i] = np.unique(np.concatenate([boundaries_[k] for k in boundaries_[i]]))
732
- cdef int num_dims = len(idx)-1
733
- boundaries = [np.asarray(boundaries_[idx[i]:idx[i+1]], dtype=np.int32).T for i in range(num_dims)]
734
- boundaries[0] = np.arange(boundaries[0].shape[1])[None,:]
735
- filtrations = s.get_filtrations()
736
- num_parameters = s.num_parameters
737
- filtrations=tuple(filtrations[idx[i]:idx[i+1]] for i in range(num_dims)) # TODO : optimize ?
738
- st = SimplexTreeMulti(num_parameters = num_parameters, dtype = s.dtype, kcritical=s.is_kcritical)
739
- for dim in range(num_dims):
740
- if s.is_kcritical: ## TODO : this may be very slow
741
- # for b,f in zip(boundaries[i].T,filtrations[i]):
742
- # for g in np.asarray(f):
743
- # st.insert(np.asarray(b, dtype = np.int32),np.asarray(g, dtype=s.dtype))
744
- for j in range(boundaries[i].shape[1]):
745
- splx = boundaries[i][:,j]
746
- for k in range(filtrations[i][j]):
747
- st.insert(splx, np.asarray(filtrations[i][j][k], dtype = s.dtype))
748
- else:
749
- st.insert_batch(np.asarray(boundaries[dim], dtype= np.int32),np.asarray(filtrations[dim], dtype=s.dtype))
750
- return st
751
-
752
-
753
- def _is_slicer(object input)->bool:
754
- """
755
- Checks if the input is a slicer. Equivalent (but faster) to `isinstance(input, multipers.slicer.Slicer_type)`.
756
- """
757
- return (False
758
- {{for D in slicers}}
759
- or isinstance(input, {{D['PYTHON_TYPE']}})
760
- {{endfor}}
761
- )
762
- def is_slicer(input, bool allow_minpres=True)->bool:
763
- if _is_slicer(input):
764
- return True
765
- if allow_minpres and isinstance(input, list) or isinstance(input, tuple):
766
- if len(input)>0 and all((_is_slicer(s) and s.is_minpres for s in input)):
767
- return True
768
- return False
769
-
770
-
771
- def to_blocks(input):
772
- """
773
- Converts input to blocks, if possible.
774
- """
775
- if is_slicer(input):
776
- return slicer2blocks(input)
777
- if isinstance(input, list) or isinstance(input, tuple):
778
- return input
779
- from multipers.simplex_tree_multi import is_simplextree_multi
780
- if is_simplextree_multi(input):
781
- return input._to_scc()
782
- if isinstance(input, str) or isinstance(input, os.PathLike):
783
- return mio.scc_parser(input)
784
- raise ValueError("Input cannot be converted to blocks.")
785
-
786
-
787
- def get_matrix_slicer(bool is_vineyard, bool is_k_critical, dtype:type|_valid_dtypes, str col, str pers_backend):
788
- """
789
- Given various parameters, returns the specific slicer type associated with them.
790
- """
791
- if False:
792
- pass
793
- {{for D in slicers}}
794
- {{if not D['IS_SIMPLICIAL']}}
795
- elif is_vineyard == {{D['IS_VINE']}} and is_k_critical == {{D['IS_KCRITICAL']}} and np.dtype(dtype) is np.dtype({{D['PY_VALUE_TYPE']}}) and col.lower() == "{{D['COLUMN_TYPE']}}".lower() and "{{D['PERS_BACKEND_TYPE']}}".lower() == pers_backend.lower():
796
- return {{D['PYTHON_TYPE']}}
797
- {{endif}}
798
- {{endfor}}
799
- else:
800
- raise ValueError(f"Unimplemented combo for {pers_backend} : {is_vineyard=}, {is_k_critical=}, {dtype=}, {col=}")
801
-
802
-
803
-
804
-
805
- def _hilbert_signed_measure(slicer,
806
- vector[indices_type] degrees,
807
- bool zero_pad=False,
808
- indices_type n_jobs=0,
809
- bool verbose=False,
810
- # bool expand_collapse=False,
811
- # grid_conversion = None,
812
- bool ignore_inf = True,
813
- ):
814
- """
815
- Computes the signed measures given by the decomposition of the hilbert function.
816
-
817
- Input
818
- -----
819
-
820
- - simplextree:SimplexTreeMulti, the multifiltered simplicial complex
821
- - degrees:array-like of ints, the degrees to compute
822
- - n_jobs:int, number of jobs. Defaults to #cpu, but when doing parallel computations of signed measures, we recommend setting this to 1.
823
- - verbose:bool, prints c++ logs.
824
-
825
- Output
826
- ------
827
-
828
- `[signed_measure_of_degree for degree in degrees]`
829
- with `signed_measure_of_degree` of the form `(dirac location, dirac weights)`.
830
- """
831
-
832
- assert slicer.is_squeezed, "Squeeze grid first."
833
- if slicer.is_squeezed:
834
- grid_shape = np.array([len(f) for f in slicer.filtration_grid])
835
- else:
836
- grid_shape = (slicer.filtration_bounds()[1]).astype(python_indices_type)+1
837
- if zero_pad:
838
- for i, _ in enumerate(grid_shape):
839
- grid_shape[i] += 1 # adds a 0
840
- assert len(grid_shape) == slicer.num_parameters, "Grid shape size has to be the number of parameters."
841
- grid_shape_with_degree = np.asarray(np.concatenate([[len(degrees)], grid_shape]), dtype=python_indices_type)
842
- container_array = np.ascontiguousarray(np.zeros(grid_shape_with_degree, dtype=python_tensor_dtype).flatten())
843
- assert len(container_array) < np.iinfo(np.uint32).max, "Too large container. Raise an issue on github if you encounter this issue. (Due to tensor's operator[])"
844
- cdef vector[indices_type] c_grid_shape = grid_shape_with_degree
845
- cdef tensor_dtype[::1] container = container_array
846
- cdef tensor_dtype* container_ptr = &container[0]
847
- cdef signed_measure_type out = _compute_hilbert_sm(slicer, container_ptr, c_grid_shape, degrees,n_jobs, verbose, zero_pad, ignore_inf)
848
- pts, weights = np.asarray(out.first, dtype=python_indices_type).reshape(-1, slicer.num_parameters+1), np.asarray(out.second, dtype=python_tensor_dtype)
849
- slices = np.concatenate([np.searchsorted(pts[:,0], np.arange(degrees.size())), [pts.shape[0]] ])
850
- sms = [
851
- (pts[slices[i]:slices[i+1],1:],weights[slices[i]:slices[i+1]])
852
- for i in range(slices.shape[0]-1)
853
- ]
854
- return sms
855
-
856
-
857
- ## Rank invariant
858
-
859
-
860
- ## TODO : It is not necessary to do the Möbius inversion in python.
861
- ## fill rank in flipped death, then differentiate in cpp, then reflip with numpy.
862
- def _rank_from_slicer(
863
- slicer,
864
- vector[indices_type] degrees,
865
- bool verbose=False,
866
- indices_type n_jobs=1,
867
- bool zero_pad = False,
868
- grid_shape=None,
869
- bool plot=False,
870
- bool return_raw=False,
871
- bool ignore_inf = True,
872
- ):
873
- # cdef intptr_t slicer_ptr = <intptr_t>(slicer.get_ptr())
874
- if grid_shape is None:
875
- if slicer.is_squeezed:
876
- grid_shape = np.array([len(f) for f in slicer.filtration_grid])
877
- else:
878
- grid_shape = (slicer.filtration_bounds()[1]).astype(python_indices_type)+1
879
- grid_shape = np.asarray(grid_shape)
880
-
881
- cdef int num_parameters = len(grid_shape)
882
-
883
- if zero_pad:
884
- for i, _ in enumerate(grid_shape):
885
- grid_shape[i] += 1 # adds a 0
886
- # for i,f in enumerate(grid_conversion):
887
- # grid_conversion[i] = np.concatenate([f, [mass_default[i]]])
888
-
889
- grid_shape_with_degree = np.asarray(np.concatenate([[len(degrees)], grid_shape, grid_shape]), dtype=python_indices_type)
890
- container_array = np.ascontiguousarray(np.zeros(grid_shape_with_degree, dtype=python_tensor_dtype).ravel())
891
- assert len(container_array) < np.iinfo(python_indices_type).max, "Too large container. Raise an issue on github if you encounter this issue. (Due to tensor's operator[])"
892
- cdef vector[indices_type] c_grid_shape = grid_shape_with_degree
893
- cdef tensor_dtype[::1] container = container_array
894
- cdef tensor_dtype* container_ptr = &container[0]
895
-
896
- ## SLICERS
897
- _compute_rank_invariant(slicer, container_ptr, c_grid_shape, degrees, n_jobs, ignore_inf)
898
-
899
- rank = container_array.reshape(grid_shape_with_degree)
900
- rank = tuple(rank_decomposition_by_rectangles(rank_of_degree, threshold = zero_pad) for rank_of_degree in rank)
901
- if return_raw:
902
- return rank
903
- out = []
904
- def clean_rank(rank_decomposition):
905
- (coords, weights) = sparsify(np.ascontiguousarray(rank_decomposition))
906
- births = coords[:,:num_parameters]
907
- deaths = coords[:,num_parameters:]
908
- correct_indices = np.all(births<=deaths, axis=1)
909
- coords = coords[correct_indices]
910
- weights = weights[correct_indices]
911
- return coords, weights
912
-
913
- out = tuple(clean_rank(rank_decomposition) for rank_decomposition in rank)
914
- return out
1
+ {{py:
2
+
3
+ """
4
+ Vine and non-vine slicers.
5
+ both type have the same interface, defined the slicer.pyx file
6
+ """
7
+
8
+
9
+ import pickle
10
+
11
+ with open("build/tmp/_slicer_names.pkl", "rb") as f:
12
+ slicers=pickle.load(f)
13
+
14
+
15
+ }}
16
+
17
+ from multipers.simplex_tree_multi import SimplexTreeMulti, SimplexTreeMulti_type
18
+ import multipers
19
+ from typing import Optional,Literal
20
+ import threading
21
+ import os
22
+ from joblib import Parallel, delayed
23
+
24
+ from multipers.slicer cimport *
25
+ from multipers.filtrations cimport *
26
+ from multipers.filtration_conversions cimport *
27
+ ## TODO: these two are not needed, remove that by updating rank code.
28
+ from multipers.point_measure import sparsify, rank_decomposition_by_rectangles
29
+ from multipers.grids import compute_grid
30
+
31
+ import numpy as np
32
+ cimport cython
33
+ from libcpp.string cimport string
34
+ # python_value_type = np.float32
35
+ from typing import Union
36
+ from cython.operator cimport dereference
37
+
38
+ ## WARNING : This is repeated in the pxd file ...
39
+ python_indices_type=np.int32
40
+ python_tensor_dtype = np.int32
41
+
42
+ global available_slicers
43
+ available_slicers = tuple((
44
+ {{for D in slicers}}
45
+ {{D['PYTHON_TYPE']}},
46
+ {{endfor}}
47
+ ))
48
+
49
+ global available_columns
50
+ available_columns = set((
51
+ {{for D in slicers}}
52
+ "{{D['COLUMN_TYPE']}}",
53
+ {{endfor}}
54
+ ))
55
+
56
+ global available_dtype
57
+ available_dtype = set([
58
+ {{for D in slicers}}
59
+ "{{D['PY_VALUE_TYPE']}}",
60
+ {{endfor}}
61
+ ])
62
+
63
+
64
+ global available_pers_backend
65
+ available_pers_backend = set([
66
+ {{for D in slicers}}
67
+ "{{D['PERS_BACKEND_TYPE']}}",
68
+ {{endfor}}
69
+ ])
70
+
71
+
72
+
73
+ global column_type
74
+ _column_type = Literal[
75
+ {{for D in slicers}}
76
+ "{{D['COLUMN_TYPE']}}",
77
+ {{endfor}}
78
+ ]
79
+
80
+ global _slicers_type
81
+ Slicer_type = Union[
82
+ {{for D in slicers}}
83
+ {{D['PYTHON_TYPE']}},
84
+ {{endfor}}
85
+ ]
86
+
87
+ global _valid_dtypes
88
+ _valid_dtype = Union[
89
+ {{for D in slicers}}
90
+ {{D['PY_VALUE_TYPE']}},
91
+ {{endfor}}
92
+ ]
93
+
94
+
95
+ global _valid_pers_backend
96
+ _valid_pers_backend = Literal[
97
+ {{for D in slicers}}
98
+ "{{D['PERS_BACKEND_TYPE']}}",
99
+ {{endfor}}
100
+ ]
101
+
102
+ {{for D in slicers}}
103
+
104
+ #------------------------------------------------------------------------------
105
+ cdef class {{D['PYTHON_TYPE']}}:
106
+ cdef {{D['C_TEMPLATE_TYPE']}} truc
107
+ cdef public vector[vector[double]] filtration_grid
108
+ cdef public int minpres_degree ## TODO : maybe change directly the degree in the minpres ?
109
+
110
+ def __repr__(self):
111
+ return f"slicer[backend={self.pers_backend},dtype={np.dtype(self.dtype).name},num_param={self.num_parameters},vineyard={self.is_vine},kcritical={self.is_kcritical},is_squeezed={self.is_squeezed},is_minpres={self.is_minpres},max_dim={self.dimension}]"
112
+
113
+ @property
114
+ def is_squeezed(self)->bool:
115
+ return self.filtration_grid.size() > 0 and self.filtration_grid[0].size() > 0
116
+ @property
117
+ def is_minpres(self)->bool:
118
+ return self.minpres_degree>=0
119
+ @staticmethod
120
+ def _inf_value():
121
+ return np.asarray(np.inf,dtype={{D['PY_VALUE_TYPE']}}) if issubclass({{D['PY_VALUE_TYPE']}},np.floating) else np.iinfo({{D['PY_VALUE_TYPE']}}).max
122
+
123
+ def get_ptr(self):
124
+ """
125
+ Returns a pointer to the underlying C++ slicer.
126
+ """
127
+ return <intptr_t>(&self.truc)
128
+ def _from_ptr(self, intptr_t slicer_ptr):
129
+ self.truc = dereference(<{{D['C_TEMPLATE_TYPE']}}*>(slicer_ptr))
130
+ return self
131
+
132
+ {{if D['IS_SIMPLICIAL']}}
133
+ def __init__(self, st=None):
134
+ """
135
+ Constructs a slicer from a simplex tree.
136
+ """
137
+ pass
138
+ def __cinit__(self, st=None):
139
+ if st is None:
140
+ return
141
+ cdef intptr_t ptr = st.thisptr
142
+ cdef Simplex_tree_multi_interface[{{D['FILTRATION_TYPE']}},{{D['C_VALUE_TYPE']}}]* st_ptr = <Simplex_tree_multi_interface[{{D['FILTRATION_TYPE']}},{{D['C_VALUE_TYPE']}}]*>(ptr)
143
+ self.truc = {{D['C_TEMPLATE_TYPE']}}(st_ptr)
144
+ self.minpres_degree = -1
145
+ {{elif D['IS_KCRITICAL']}}
146
+ def __init__(self, generator_maps=[], generator_dimensions=[], filtration_values=[]):
147
+ """
148
+ Constructs a slicer from
149
+ - scc-like blocks
150
+ or
151
+ - generator maps (Iterable of list of ints)
152
+ - generator dimensions (Iterable of int)
153
+ - filtration values (Iterable of filtration values)
154
+ """
155
+ pass
156
+ def __cinit__(self, generator_maps=[], generator_dimensions=[], filtration_values=[]):
157
+ """
158
+ Cython constructor
159
+ """
160
+ if len(generator_maps)>0 and len(generator_dimensions) == 0 and len(filtration_values) == 0:
161
+ from multipers._slicer_meta import _blocks2boundary_dimension_grades
162
+ generator_maps, generator_dimensions, filtration_values = _blocks2boundary_dimension_grades(
163
+ generator_maps,
164
+ inplace=False,
165
+ )
166
+ cdef uint32_t num_generators = len(generator_maps)
167
+ cdef vector[vector[uint32_t]] c_generator_maps
168
+ cdef vector[Multi_critical_filtration[{{D['C_VALUE_TYPE']}}]] c_filtration_values
169
+ for stuff in generator_maps:
170
+ c_generator_maps.push_back(<vector[uint32_t]>(stuff))
171
+ cdef Multi_critical_filtration[{{D['C_VALUE_TYPE']}}] cf
172
+ cdef One_critical_filtration[{{D['C_VALUE_TYPE']}}] inf
173
+ inf[0] = -inf[0]
174
+ cdef {{D['C_VALUE_TYPE']}}[:,:] F_view
175
+ for F in filtration_values:
176
+ cf.push_to_least_common_upper_bound(inf)
177
+ F_view = np.asarray(F, dtype = {{D['PY_VALUE_TYPE']}} )
178
+ for i in range(F_view.shape[0]):
179
+ cf.add_generator(_py21c_{{D['SHORT_VALUE_TYPE']}}(F_view[i]))
180
+ c_filtration_values.push_back(cf)
181
+ cdef vector[int] c_generator_dimensions = generator_dimensions
182
+ assert num_generators == c_generator_maps.size() == c_filtration_values.size(), "Invalid input, shape do not coincide."
183
+ self.truc = {{D['C_TEMPLATE_TYPE']}}(c_generator_maps,c_generator_dimensions, c_filtration_values)
184
+ self.minpres_degree = -1
185
+ {{else}}
186
+ def __init__(self, generator_maps=[], generator_dimensions=[], filtration_values=[]):
187
+ """
188
+ Constructs a slicer from
189
+ - generator maps (Iterable of list of ints)
190
+ - generator dimensions (Iterable of int)
191
+ - filtration values (Iterable of filtration values)
192
+ """
193
+ pass
194
+ @cython.boundscheck(False)
195
+ @cython.wraparound(False)
196
+ def __cinit__(self, generator_maps=[], generator_dimensions=[], filtration_values=[]):
197
+ """
198
+ Cython constructor
199
+ """
200
+ cdef uint32_t num_generators = len(generator_maps)
201
+ filtration_values = np.asarray(filtration_values, dtype = {{D['PY_VALUE_TYPE']}} )
202
+ assert len(filtration_values) == num_generators, f"Invalid input, shape do not coicide. Got sizes {num_generators,len(generator_dimensions),len(filtration_values)}."
203
+ cdef vector[vector[uint32_t]] c_generator_maps
204
+ cdef vector[One_critical_filtration[{{D['C_VALUE_TYPE']}}]] c_filtration_values
205
+
206
+ c_generator_maps.resize(num_generators)
207
+ c_filtration_values.resize(num_generators)
208
+ for i in range(num_generators):
209
+ c_generator_maps[i] = <vector[uint32_t]>(generator_maps[i])
210
+ c_filtration_values[i] = _py21c_{{D['SHORT_VALUE_TYPE']}}(filtration_values[i])
211
+ cdef vector[int] c_generator_dimensions = generator_dimensions
212
+
213
+ assert num_generators == c_generator_maps.size() == c_filtration_values.size() == c_generator_dimensions.size(), "Invalid input, shape do not coincide."
214
+ self.truc = {{D['C_TEMPLATE_TYPE']}}(c_generator_maps,c_generator_dimensions, c_filtration_values)
215
+ self.minpres_degree = -1
216
+ {{endif}}
217
+
218
+ def copy(self)->{{D['PYTHON_TYPE']}}:
219
+ """
220
+ Returns a copy of the slicer.
221
+ """
222
+ copy_ = {{D['PYTHON_TYPE']}}()
223
+ copy_.truc = self.truc
224
+ copy_.minpres_degree = self.minpres_degree
225
+ copy_.filtration_grid = self.filtration_grid
226
+ return copy_
227
+ def get_barcode(self, bool keep_inf = False):
228
+ """
229
+ Returns the current barcode.
230
+ """
231
+ if keep_inf:
232
+ bcs = tuple(np.asarray(stuff, dtype = {{D['PY_VALUE_TYPE']}}) for stuff in self.truc.get_barcode())
233
+ else:
234
+ bcs = {{D['PYTHON_TYPE']}}._threshold_bcs(self.truc.get_barcode())
235
+ return self.truc.get_barcode()
236
+ def push_to_line(self, basepoint, direction=None)->{{D['PYTHON_TYPE']}}:
237
+ """
238
+ Pushes the current slicer to the line defined by a basepoint and an optional direction.
239
+ If the direction is not provided, it is assumed to be diagonal.
240
+ """
241
+ basepoint = np.asarray(basepoint, dtype = {{D['PY_VALUE_TYPE']}})
242
+ cdef Line[{{D['C_VALUE_TYPE']}}] line
243
+ if direction is None:
244
+ line = Line[{{D['C_VALUE_TYPE']}}](_py21c_{{D['SHORT_VALUE_TYPE']}}(basepoint))
245
+ else:
246
+ direction = np.asarray(direction, dtype = {{D['PY_VALUE_TYPE']}})
247
+ line = Line[{{D['C_VALUE_TYPE']}}](_py21c_{{D['SHORT_VALUE_TYPE']}}(basepoint),_py21c_{{D['SHORT_VALUE_TYPE']}}(direction))
248
+ self.truc.push_to(line)
249
+ return self
250
+
251
+ @staticmethod
252
+ cdef _threshold_bcs(vector[vector[pair[{{D['C_VALUE_TYPE']}}, {{D['C_VALUE_TYPE']}}]]] bcs):
253
+ return tuple(np.fromiter((a for a in stuff if a.first < {{D['PYTHON_TYPE']}}._inf_value()), dtype=np.dtype(({{D['PY_VALUE_TYPE']}},2))) for stuff in bcs)
254
+ @staticmethod
255
+ def _bc_to_full(bcs, basepoint, direction=None):
256
+ # i, (b sv d), coords
257
+ basepoint = np.asarray(basepoint)[None,None,:]
258
+ direction = 1 if direction is None else np.asarray(direction)[None,None,:]
259
+ return tuple(bc[:,:,None]*direction + basepoint for bc in bcs)
260
+
261
+ def persistence_on_line(self,basepoint,direction=None, bool keep_inf=True, bool full=False):
262
+ """
263
+ Computes the persistence on a line L defined by
264
+ - a basepoint (num_parameters,) array
265
+ - an optional direction (num_parameters,) array
266
+
267
+ Warning: This is not parallelizable. Use `persitence_on_lines`.
268
+ """
269
+ self.push_to_line(basepoint,direction)
270
+ self.truc.compute_persistence()
271
+ if keep_inf:
272
+ bcs = tuple(np.asarray(stuff, dtype = {{D['PY_VALUE_TYPE']}}) for stuff in self.truc.get_barcode())
273
+ else:
274
+ bcs = {{D['PYTHON_TYPE']}}._threshold_bcs(self.truc.get_barcode())
275
+
276
+ if full:
277
+ bcs = {{D['PYTHON_TYPE']}}._bc_to_full(bcs, basepoint, direction)
278
+ return bcs
279
+
280
+ def persistence_on_lines(self, basepoints=None, directions=None, bool keep_inf=True, bool full=False):
281
+ """
282
+ Same as `persistence_on_line`, but with vineyards operation between
283
+ lines if `self.is_vine`, and in parallel otherwise.
284
+ """
285
+ cdef vector[vector[{{D['C_VALUE_TYPE']}}]] c_basepoints
286
+ cdef vector[pair[vector[{{D['C_VALUE_TYPE']}}], vector[{{D['C_VALUE_TYPE']}}]]] c_truc
287
+ cdef vector[vector[vector[pair[{{D['C_VALUE_TYPE']}}, {{D['C_VALUE_TYPE']}}]]]] c_out
288
+ if directions is None:
289
+ c_basepoints = basepoints
290
+ with nogil:
291
+ c_out = self.truc.persistence_on_lines(c_basepoints)
292
+ else:
293
+ c_truc = zip(basepoints,directions)
294
+ with nogil:
295
+ c_out = self.truc.persistence_on_lines(c_truc)
296
+ cdef int num_bc = c_basepoints.size()
297
+
298
+ if keep_inf:
299
+ out = tuple(tuple(np.asarray(y, dtype = {{D['PY_VALUE_TYPE']}}) for y in x) for x in c_out)
300
+ else:
301
+ out = tuple({{D['PYTHON_TYPE']}}._threshold_bcs(x) for x in c_out)
302
+
303
+ if full:
304
+ _dirs = [None]*len(basepoints) if directions is None else directions
305
+ out = tuple({{D['PYTHON_TYPE']}}._bc_to_full(bcs, bp, dir) for bcs, bp, dir in zip(out,basepoints,_dirs))
306
+ return out
307
+
308
+
309
+ def __getstate__(self):
310
+ return (
311
+ self.get_boundaries(),
312
+ self.get_dimensions(),
313
+ self.get_filtrations(),
314
+ tuple(np.array(f) for f in self.filtration_grid),
315
+ self.minpres_degree,
316
+ )
317
+ def __setstate__(self, tuple dump):
318
+ B, D, F, filtration_grid, minpres_degree = dump
319
+ copy = {{D['PYTHON_TYPE']}}(B,D,F)
320
+ self.truc = copy.truc
321
+ self.minpres_degree= minpres_degree
322
+ self.filtration_grid=filtration_grid
323
+
324
+ def __eq__(self, other):
325
+ ## True if they rpz the same complex (no reordering allowed yet),
326
+ # i.e., ignores minpres, squeeze
327
+ if other.is_squeezed:
328
+ return self == other.unsqueeze()
329
+ if self.is_squeezed:
330
+ return self.unsqueeze() == other
331
+ return (
332
+ np.array_equal(self.get_dimensions(), other.get_dimensions())
333
+ and
334
+ self.get_boundaries() == other.get_boundaries()
335
+ and
336
+ ## Kcritical are sorted + filtrationvalues is a dump.
337
+ # for non kcritical there is an unnecessary copy though
338
+ np.array_equal(self.get_filtrations_values(), other.get_filtrations_values())
339
+ )
340
+
341
+
342
+
343
+ def compute_persistence(self,one_filtration=None, bool ignore_infinite_filtration_values = True)->{{D['PYTHON_TYPE']}}:
344
+ """
345
+ Computes the current persistence, or the persistence
346
+ given by the filtration one_filtration (num_generators,).
347
+ """
348
+ if one_filtration is not None:
349
+ self.truc.set_one_filtration(one_filtration)
350
+ # TODO: Later
351
+ # if len(degrees)>0:
352
+ # self.truc.compute_persistence(degrees)
353
+ # else:
354
+ # self.truc.compute_persistence()
355
+ self.truc.compute_persistence(ignore_infinite_filtration_values)
356
+ return self
357
+ # return self.truc.get_barcode()
358
+ def get_barcode(self):
359
+ """
360
+ Returns the barcode of the current 1d-persistence.
361
+ """
362
+ return self.truc.get_barcode()
363
+ def sliced_filtration(self,basepoint, direction=None):
364
+ """
365
+ Computes the filtration on a line L defined by
366
+ - a basepoint (num_parameters,) array
367
+ - an optional direction (num_parameters,) array
368
+ """
369
+ self.push_to_line(basepoint,direction)
370
+ return np.asarray(self.truc.get_one_filtration())
371
+ def __len__(self):
372
+ return self.truc.num_generators()
373
+ @property
374
+ def num_generators(self):
375
+ return self.truc.num_generators()
376
+ @property
377
+ def num_parameters(self):
378
+ return self.truc.num_parameters()
379
+ @property
380
+ def info(self):
381
+ print(self.truc.to_str().decode())
382
+ def filtration_bounds(self) -> np.ndarray:
383
+ """
384
+ Computes the bounding box of the current multifiltration.
385
+ """
386
+ cdef pair[One_critical_filtration[{{D['C_VALUE_TYPE']}}],One_critical_filtration[{{D['C_VALUE_TYPE']}}]] box = self.truc.get_bounding_box()
387
+ cdef cnp.ndarray[{{D['C_VALUE_TYPE']}}, ndim=1] a = _ff21cview_{{D['SHORT_VALUE_TYPE']}}(&box.first)
388
+ cdef cnp.ndarray[{{D['C_VALUE_TYPE']}}, ndim=1] b = _ff21cview_{{D['SHORT_VALUE_TYPE']}}(&box.second)
389
+ return np.asarray([a,b])
390
+ def get_filtrations_values(self)->np.ndarray:
391
+ """
392
+ Returns the current filtration values of the slicer.
393
+ """
394
+ cdef vector[One_critical_filtration[{{D['C_VALUE_TYPE']}}]] v = self.truc.get_filtration_values()
395
+ out = _vff21cview_{{D['SHORT_VALUE_TYPE']}}(v, copy=True, duplicate=self.num_parameters)
396
+ return np.asarray(out)
397
+ def get_filtration_grid(self,grid_strategy:str="exact", **infer_grid_kwargs):
398
+ return compute_grid(
399
+ self.get_filtrations_values().T,
400
+ strategy=grid_strategy,
401
+ **infer_grid_kwargs,
402
+ )
403
+ def get_filtrations(self):
404
+ """
405
+ Returns a view of the filtration values, as a list of numpy arrays.
406
+ """
407
+ {{if D['IS_KCRITICAL']}}
408
+ return _vff2kcview_{{D['SHORT_VALUE_TYPE']}}(self.truc.get_filtrations(), copy=False, duplicate=self.num_parameters)
409
+ {{else}}
410
+ return _vff21cview_{{D['SHORT_VALUE_TYPE']}}(self.truc.get_filtrations(), copy=False, duplicate=self.num_parameters)
411
+ {{endif}}
412
+
413
+ def get_dimensions(self)-> np.ndarray:
414
+ """
415
+ Returns the ordered dimensions of the generators.
416
+ """
417
+ return np.asarray(self.truc.get_dimensions())
418
+ @property
419
+ def dimension(self)-> int:
420
+ """
421
+ Returns the maximum dimension of the complex.
422
+ """
423
+ return self.get_dimensions()[-1] if len(self)>0 else -np.inf
424
+ def prune_above_dimension(self,int max_dimension)->{{D['PYTHON_TYPE']}}:
425
+ """
426
+ Prunes the generators above a given dimension.
427
+ """
428
+ self.truc.prune_above_dimension(max_dimension)
429
+ return self
430
+ def get_boundaries(self)->tuple[tuple]:
431
+ """
432
+ Returns the boundaries of the generators.
433
+ """
434
+ return tuple(tuple(b) for b in self.truc.get_boundaries())
435
+ def grid_squeeze(self, filtration_grid=None, grid_strategy="exact", resolution:Optional[int]=None, bool coordinates=True, bool inplace = False, bool force=False)->{{D['PYTHON_TYPE'][:-3]+"i32"}}|{{D['PYTHON_TYPE']}}:
436
+ """
437
+ Coarsen the filtration values on a grid. This is necessary to compute some invariants.
438
+
439
+ If the filtration grid is not given, it is infered from filtration values,
440
+ using the :func:`multipers.grids.compute_grid` function, whose args are
441
+ - grid_strategy:str see `multipers.grids.available_strategies`. Defaults to exact.
442
+ - resolution:int if strategy is not exact.
443
+
444
+ - inplace:bool if true, does the operation inplace, i.e., doesn't return a copy.
445
+ """
446
+ if not force and self.is_squeezed:
447
+ raise ValueError("The slicer seems to be already squeezed. Use force=True to resqueeze.")
448
+ if filtration_grid is None:
449
+ filtration_grid = compute_grid(
450
+ self.get_filtrations_values().T,
451
+ strategy=grid_strategy,
452
+ resolution=resolution)
453
+ cdef vector[vector[{{D['C_VALUE_TYPE']}}]] grid = filtration_grid
454
+ if inplace or not coordinates:
455
+ self.truc.coarsen_on_grid_inplace(grid, coordinates)
456
+ self.filtration_grid = filtration_grid
457
+ else:
458
+ {{if D['COLUMN_TYPE'] is None}}
459
+ raise ValueError("WIP")
460
+ {{else}}
461
+ out = {{D['PYTHON_TYPE'][:-3]+"i32"}}()
462
+ out.truc = self.truc.coarsen_on_grid(grid)
463
+ out.filtration_grid = filtration_grid
464
+ out.minpres_degree = self.minpres_degree
465
+ return out
466
+ {{endif}}
467
+ return self
468
+ def minpres(self,
469
+ int degree=-1,
470
+ list[int] degrees=[],
471
+ str backend:Literal["mpfree", "2pac"]="mpfree",
472
+ str slicer_backend:Literal["matrix","clement","graph"]="matrix",
473
+ bool vineyard={{D['IS_VINE']}},
474
+ id :Optional[str] = None,
475
+ dtype = {{D['PY_VALUE_TYPE']}},
476
+ **minpres_kwargs
477
+ )->Slicer_type:
478
+ """
479
+ Computes the minimal presentation of the slicer, and returns it as a new slicer.
480
+ See :func:`multipers.slicer.minimal_presentation`.
481
+ """
482
+ new_slicer = minimal_presentation(self, degree=degree, degrees=degrees, backend=backend, slicer_backend=slicer_backend, vineyard=vineyard, id=id, **minpres_kwargs)
483
+ return new_slicer
484
+
485
+ @property
486
+ def dtype(self)->type:
487
+ return {{D['PY_VALUE_TYPE']}}
488
+ @property
489
+ def col_type(self)->str:
490
+ return "{{D['COLUMN_TYPE']}}"
491
+ @property
492
+ def is_vine(self)->bool:
493
+ return {{D['IS_VINE']}}
494
+ @property
495
+ def is_kcritical(self)->bool:
496
+ return {{D['IS_KCRITICAL']}}
497
+
498
+ @property
499
+ def pers_backend(self)->str:
500
+ return "{{D['PERS_BACKEND_TYPE']}}"
501
+
502
+ {{if D['IS_VINE']}}
503
+ def vine_update(self,basepoint,direction=None)->{{D['PYTHON_TYPE']}}:
504
+ """
505
+ Updates the barcode, on a line, using the vineyard algorithm.
506
+ """
507
+ self.push_to_line(basepoint,direction)
508
+ self.truc.vineyard_update()
509
+ return self
510
+ def get_representative_cycles(self, bool update=True, bool detailed=False):
511
+ """
512
+ Returns the representative cycles of the current barcode.
513
+ Recomputes the generators if update=True
514
+ """
515
+ return self.truc.get_representative_cycles(update, detailed)
516
+ def get_permutation(self):
517
+ """
518
+ Returns the current generator permutation (w.r.t. vineyard).
519
+ """
520
+ return self.truc.get_current_order()
521
+ {{endif}}
522
+
523
+ def to_scc(
524
+ self,
525
+ path:os.PathLike,
526
+ int num_parameters = -1,
527
+ int degree = -1,
528
+ bool rivet_compatible = False,
529
+ bool ignore_last_generators = False,
530
+ bool strip_comments = False,
531
+ bool reverse = False,
532
+ bool unsqueeze = True,
533
+ ):
534
+ """
535
+ Writes current slicer to a file in scc format.
536
+ """
537
+ if degree == -1 and not rivet_compatible:
538
+ degree = 1
539
+ cdef string c_path = path.encode(encoding="utf-8")
540
+ if self.is_squeezed and unsqueeze:
541
+ kwargs = locals()
542
+ kwargs.pop("self",0)
543
+ kwargs.pop("c_path",0)
544
+ self.unsqueeze().to_scc(**kwargs)
545
+ return
546
+ with nogil:
547
+ self.truc.write_to_scc_file(c_path, num_parameters, degree, rivet_compatible, ignore_last_generators, strip_comments, reverse)
548
+
549
+ {{if not D['IS_KCRITICAL']}}
550
+ def _build_from_scc_file(self, path:os.PathLike, bool rivet_compatible = False, bool reverse = False, int shift_dimension = 0)->{{D['PYTHON_TYPE']}}:
551
+ """
552
+ Builds the slicer from the given scc file. Should be empty before, otherwise will be completely overwritten.
553
+ """
554
+ cdef string c_path = path.encode(encoding="utf-8")
555
+ with nogil:
556
+ self.truc.build_from_scc_file(c_path, rivet_compatible, reverse, shift_dimension)
557
+ return self
558
+
559
+ def unsqueeze(self, grid=None, dtype = np.float64):
560
+ from multipers.grids import evaluate_in_grid
561
+ from multipers import Slicer
562
+ grid = tuple(np.asarray(f) for f in self.filtration_grid) if grid is None else grid
563
+ new_filtrations = evaluate_in_grid(np.asarray(self.get_filtrations(), dtype=np.int32), grid)
564
+ new_slicer = {{D['PYTHON_TYPE'][:-3]+"f64"}}(
565
+ self.get_boundaries(),
566
+ self.get_dimensions(),
567
+ new_filtrations,
568
+ )
569
+ new_slicer.minpres_degree=self.minpres_degree
570
+ return new_slicer
571
+ {{endif}}
572
+
573
+
574
+ {{endfor}}
575
+
576
+ from libcpp.vector cimport vector
577
+ from libcpp.set cimport set as cset
578
+ cdef extern from "gudhi/cubical_to_boundary.h" namespace "":
579
+ void _to_boundary(const vector[unsigned int]&, vector[vector[unsigned int]]&, vector[int]&) except + nogil
580
+ void get_vertices(unsigned int, cset[unsigned int]&, const vector[vector[unsigned int]]&) nogil
581
+
582
+
583
+ def from_bitmap(image, **slicer_kwargs):
584
+ from multipers import Slicer
585
+ image = np.asarray(image)
586
+ slicer_kwargs["dtype"] = slicer_kwargs.get("dtype", image.dtype)
587
+ _Slicer = Slicer(return_type_only=True, **slicer_kwargs)
588
+ cdef vector[unsigned int] img_shape = image.shape[:-1]
589
+ cdef unsigned int num_parameters = image.shape[-1]
590
+ cdef vector[vector[unsigned int]] gen_maps
591
+ cdef vector[int] gen_dims
592
+
593
+ with nogil:
594
+ _to_boundary(img_shape,gen_maps, gen_dims)
595
+
596
+ cdef unsigned int num_gens = gen_dims.size()
597
+ filtration_values = np.zeros(shape=(num_gens, num_parameters), dtype = np.double) - np.inf
598
+ cdef double[:,:] F = filtration_values
599
+ cdef double[:,:] c_img = image.reshape(-1,num_parameters)
600
+ cdef cset[unsigned int] vertices
601
+ with nogil:
602
+ for i in range(num_gens):
603
+ # with gil:
604
+ # print(f"idx {i}:", end="")
605
+ vertices.clear()
606
+ get_vertices(i,vertices,gen_maps)
607
+
608
+ # with gil:
609
+ # print(f"v = {vertices}:", end="")
610
+ for k in vertices:
611
+ for j in range(num_parameters):
612
+ F[i,j] = max(F[i,j], c_img[k,j])
613
+
614
+ # with gil:
615
+ # print(f"F = {np.asarray(F[i])}")
616
+ slicer = _Slicer(gen_maps, gen_dims, filtration_values)
617
+ return slicer
618
+
619
+ def from_function_delaunay(
620
+ points,
621
+ grades,
622
+ int degree=-1,
623
+ backend: Optional[_valid_pers_backend]=None,
624
+ vineyard:Optional[bool]=None,
625
+ dtype=np.float64,
626
+ bool verbose = False,
627
+ bool clear = True,
628
+ ):
629
+ """
630
+ Given points in $\mathbb R^n$ and function grades, compute the function-delaunay
631
+ bifiltration as a in an scc format, and converts it into a slicer.
632
+
633
+ points : (num_pts, n) float array
634
+ grades : (num_pts,) float array
635
+ degree (opt) : if given, computes a minimal presentation of this homological degree first
636
+ backend : slicer backend, e.g. "matrix", "clement"
637
+ vineyard : bool, use a vineyard-compatible backend
638
+ """
639
+ from multipers.io import _init_external_softwares, function_delaunay_presentation_to_slicer
640
+ s = multipers.Slicer(None, backend=backend, vineyard=vineyard, dtype=dtype)
641
+ _init_external_softwares(requires=["function_delaunay"])
642
+ function_delaunay_presentation_to_slicer(s, points, grades, degree=degree, verbose=verbose,clear=clear)
643
+ if degree >= 0:
644
+ s.minpres_degree = degree
645
+ return s
646
+
647
+ def slicer2blocks(slicer, int degree = -1, bool reverse=True):
648
+ """
649
+ Convert any slicer to the block format a.k.a. scc format for python
650
+ """
651
+ dims = slicer.get_dimensions()
652
+ num_empty_blocks_to_add = 1 if degree == -1 else dims.min()-degree +1
653
+ _,counts = np.unique(dims, return_counts=True, )
654
+ indices = np.concatenate([[0],counts], dtype=np.int32).cumsum()
655
+ filtration_values = slicer.get_filtrations()
656
+ filtration_values = [filtration_values[indices[i]:indices[i+1]] for i in range(len(indices)-1)]
657
+ boundaries = slicer.get_boundaries()
658
+ boundaries = [boundaries[indices[i]:indices[i+1]] for i in range(len(indices)-1)]
659
+ shift = np.concatenate([[0], indices], dtype=np.int32)
660
+ boundaries = [tuple(np.asarray(x-s, dtype=np.int32) for x in block) for s,block in zip(shift,boundaries)]
661
+ blocks = [tuple((f,tuple(b))) for b,f in zip(boundaries,filtration_values)]
662
+ blocks = ([(np.empty((0,)),[])]*num_empty_blocks_to_add) + blocks
663
+ if reverse:
664
+ blocks.reverse()
665
+ return blocks
666
+
667
+ def minimal_presentation(
668
+ slicer,
669
+ int degree = -1,
670
+ degrees:Iterable[int]=[],
671
+ str backend:Literal["mpfree", "2pac", ""]="mpfree",
672
+ str slicer_backend:Literal["matrix","clement","graph"]="matrix",
673
+ bool vineyard=True,
674
+ id :Optional[str] =None,
675
+ dtype:type|_valid_dtypes=None,
676
+ int n_jobs = -1,
677
+ bool force=False,
678
+ **minpres_kwargs
679
+ ):
680
+ """
681
+ Computes a minimal presentation of the multifiltered complex given by the slicer,
682
+ and returns it as a slicer.
683
+ Backends differents than `mpfree` are unstable.
684
+ """
685
+ from multipers.io import _init_external_softwares, input_path, scc_reduce_from_str_to_slicer
686
+ if is_slicer(slicer) and slicer.is_minpres and not force:
687
+ from warnings import warn
688
+ warn(f"The slicer seems to be already reduced, from homology of degree {slicer.minpres_degree}.")
689
+ return slicer
690
+ _init_external_softwares(requires=[backend])
691
+ if len(degrees)>0:
692
+ def todo(int degree):
693
+ return minimal_presentation(slicer, degree=degree, backend=backend, slicer_backend=slicer_backend, vineyard=vineyard, id=id, **minpres_kwargs)
694
+ return tuple(
695
+ Parallel(n_jobs=n_jobs, backend="threading")(delayed(todo)(d) for d in degrees)
696
+ )
697
+ # return tuple(minimal_presentation(slicer, degree=d, backend=backend, slicer_backend=slicer_backend, vineyard=vineyard, id=id, **minpres_kwargs) for d in degrees)
698
+ assert degree>=0, f"Degree not provided."
699
+ filtration_grid = slicer.filtration_grid if slicer.is_squeezed else None
700
+ if id is None:
701
+ id = str(threading.get_native_id())
702
+ if dtype is None:
703
+ dtype = slicer.dtype
704
+ dimension = slicer.dimension - degree # latest = L-1, which is empty, -1 for degree 0, -2 for degree 1 etc.
705
+ slicer.to_scc(path=input_path+id, strip_comments=True, degree=degree-1)
706
+ new_slicer = multipers.Slicer(None,backend=slicer_backend, vineyard=vineyard, dtype=dtype)
707
+ if backend=="mpfree":
708
+ shift_dimension=degree-1
709
+ else:
710
+ shift_dimension=degree
711
+ scc_reduce_from_str_to_slicer(path=input_path+id, slicer=new_slicer, dimension=dimension, backend=backend, shift_dimension=shift_dimension, **minpres_kwargs)
712
+ new_slicer.minpres_degree = degree
713
+ if filtration_grid is not None:
714
+ new_slicer.filtration_grid = filtration_grid
715
+ return new_slicer
716
+
717
+
718
+ def to_simplextree(s:Slicer_type, max_dim:int=-1) -> SimplexTreeMulti_type:
719
+ """
720
+ Turns a --simplicial-- slicer into a simplextree.
721
+
722
+ Warning: Won't work for non-simplicial complexes,
723
+ i.e., complexes $K$ not satisfying
724
+ $\forall \sigma \in K,\, \mathrm{dim}(\sigma) = |\partial \sigma|-1$
725
+ """
726
+ dims = s.get_dimensions()
727
+ assert np.all(dims[:-1] <= dims[1:]), "Dims is not sorted."
728
+ idx = np.searchsorted(dims, np.unique(dims))
729
+ idx = np.concatenate([idx, [dims.shape[0]]])
730
+ if max_dim>=0:
731
+ idx = idx[:max_dim+2]
732
+
733
+ cdef vector[vector[int]] boundaries_ = s.get_boundaries()
734
+ cdef int a
735
+ cdef int b
736
+ if len(idx)>2:
737
+ a = idx[2]
738
+ b = idx[-1]
739
+ for i in range(a, b):
740
+ boundaries_[i] = np.unique(np.concatenate([boundaries_[k] for k in boundaries_[i]]))
741
+ cdef int num_dims = len(idx)-1
742
+ boundaries = [np.asarray(boundaries_[idx[i]:idx[i+1]], dtype=np.int32).T for i in range(num_dims)]
743
+ boundaries[0] = np.arange(boundaries[0].shape[1])[None,:]
744
+ filtrations = s.get_filtrations()
745
+ num_parameters = s.num_parameters
746
+ filtrations=tuple(filtrations[idx[i]:idx[i+1]] for i in range(num_dims)) # TODO : optimize ?
747
+ st = SimplexTreeMulti(num_parameters = num_parameters, dtype = s.dtype, kcritical=s.is_kcritical)
748
+ for dim in range(num_dims):
749
+ if s.is_kcritical: ## TODO : this may be very slow
750
+ # for b,f in zip(boundaries[i].T,filtrations[i]):
751
+ # for g in np.asarray(f):
752
+ # st.insert(np.asarray(b, dtype = np.int32),np.asarray(g, dtype=s.dtype))
753
+ for j in range(boundaries[i].shape[1]):
754
+ splx = boundaries[i][:,j]
755
+ for k in range(filtrations[i][j]):
756
+ st.insert(splx, np.asarray(filtrations[i][j][k], dtype = s.dtype))
757
+ else:
758
+ st.insert_batch(np.asarray(boundaries[dim], dtype= np.int32),np.asarray(filtrations[dim], dtype=s.dtype))
759
+ return st
760
+
761
+
762
+ def _is_slicer(object input)->bool:
763
+ """
764
+ Checks if the input is a slicer. Equivalent (but faster) to `isinstance(input, multipers.slicer.Slicer_type)`.
765
+ """
766
+ return (False
767
+ {{for D in slicers}}
768
+ or isinstance(input, {{D['PYTHON_TYPE']}})
769
+ {{endfor}}
770
+ )
771
+ def is_slicer(input, bool allow_minpres=True)->bool:
772
+ if _is_slicer(input):
773
+ return True
774
+ if allow_minpres and isinstance(input, list) or isinstance(input, tuple):
775
+ if len(input)>0 and all((_is_slicer(s) and s.is_minpres for s in input)):
776
+ return True
777
+ return False
778
+
779
+
780
+ def to_blocks(input):
781
+ """
782
+ Converts input to blocks, if possible.
783
+ """
784
+ if is_slicer(input):
785
+ return slicer2blocks(input)
786
+ if isinstance(input, list) or isinstance(input, tuple):
787
+ return input
788
+ from multipers.simplex_tree_multi import is_simplextree_multi
789
+ if is_simplextree_multi(input):
790
+ return input._to_scc()
791
+ if isinstance(input, str) or isinstance(input, os.PathLike):
792
+ from multipers.io import scc_parser
793
+ return scc_parser(input)
794
+ raise ValueError("Input cannot be converted to blocks.")
795
+
796
+
797
+ def get_matrix_slicer(bool is_vineyard, bool is_k_critical, dtype:type|_valid_dtypes, str col, str pers_backend):
798
+ """
799
+ Given various parameters, returns the specific slicer type associated with them.
800
+ """
801
+ if False:
802
+ pass
803
+ {{for D in slicers}}
804
+ {{if not D['IS_SIMPLICIAL']}}
805
+ elif is_vineyard == {{D['IS_VINE']}} and is_k_critical == {{D['IS_KCRITICAL']}} and np.dtype(dtype) is np.dtype({{D['PY_VALUE_TYPE']}}) and col.lower() == "{{D['COLUMN_TYPE']}}".lower() and "{{D['PERS_BACKEND_TYPE']}}".lower() == pers_backend.lower():
806
+ return {{D['PYTHON_TYPE']}}
807
+ {{endif}}
808
+ {{endfor}}
809
+ else:
810
+ raise ValueError(f"Unimplemented combo for {pers_backend} : {is_vineyard=}, {is_k_critical=}, {dtype=}, {col=}")
811
+
812
+
813
+
814
+
815
+ def _hilbert_signed_measure(slicer,
816
+ vector[indices_type] degrees,
817
+ bool zero_pad=False,
818
+ indices_type n_jobs=0,
819
+ bool verbose=False,
820
+ # bool expand_collapse=False,
821
+ # grid_conversion = None,
822
+ bool ignore_inf = True,
823
+ ):
824
+ """
825
+ Computes the signed measures given by the decomposition of the hilbert function.
826
+
827
+ Input
828
+ -----
829
+
830
+ - simplextree:SimplexTreeMulti, the multifiltered simplicial complex
831
+ - degrees:array-like of ints, the degrees to compute
832
+ - n_jobs:int, number of jobs. Defaults to #cpu, but when doing parallel computations of signed measures, we recommend setting this to 1.
833
+ - verbose:bool, prints c++ logs.
834
+
835
+ Output
836
+ ------
837
+
838
+ `[signed_measure_of_degree for degree in degrees]`
839
+ with `signed_measure_of_degree` of the form `(dirac location, dirac weights)`.
840
+ """
841
+
842
+ assert slicer.is_squeezed, "Squeeze grid first."
843
+ if slicer.is_squeezed:
844
+ grid_shape = np.array([len(f) for f in slicer.filtration_grid])
845
+ else:
846
+ grid_shape = (slicer.filtration_bounds()[1]).astype(python_indices_type)+1
847
+ if zero_pad:
848
+ for i, _ in enumerate(grid_shape):
849
+ grid_shape[i] += 1 # adds a 0
850
+ assert len(grid_shape) == slicer.num_parameters, "Grid shape size has to be the number of parameters."
851
+ grid_shape_with_degree = np.asarray(np.concatenate([[len(degrees)], grid_shape]), dtype=python_indices_type)
852
+ container_array = np.ascontiguousarray(np.zeros(grid_shape_with_degree, dtype=python_tensor_dtype).flatten())
853
+ assert len(container_array) < np.iinfo(np.uint32).max, "Too large container. Raise an issue on github if you encounter this issue. (Due to tensor's operator[])"
854
+ cdef vector[indices_type] c_grid_shape = grid_shape_with_degree
855
+ cdef tensor_dtype[::1] container = container_array
856
+ cdef tensor_dtype* container_ptr = &container[0]
857
+ cdef signed_measure_type out = _compute_hilbert_sm(slicer, container_ptr, c_grid_shape, degrees,n_jobs, verbose, zero_pad, ignore_inf)
858
+ pts, weights = np.asarray(out.first, dtype=python_indices_type).reshape(-1, slicer.num_parameters+1), np.asarray(out.second, dtype=python_tensor_dtype)
859
+ slices = np.concatenate([np.searchsorted(pts[:,0], np.arange(degrees.size())), [pts.shape[0]] ])
860
+ sms = [
861
+ (pts[slices[i]:slices[i+1],1:],weights[slices[i]:slices[i+1]])
862
+ for i in range(slices.shape[0]-1)
863
+ ]
864
+ return sms
865
+
866
+
867
+ ## Rank invariant
868
+
869
+
870
+ ## TODO : It is not necessary to do the Möbius inversion in python.
871
+ ## fill rank in flipped death, then differentiate in cpp, then reflip with numpy.
872
+ def _rank_from_slicer(
873
+ slicer,
874
+ vector[indices_type] degrees,
875
+ bool verbose=False,
876
+ indices_type n_jobs=1,
877
+ bool zero_pad = False,
878
+ grid_shape=None,
879
+ bool plot=False,
880
+ bool return_raw=False,
881
+ bool ignore_inf = True,
882
+ ):
883
+ # cdef intptr_t slicer_ptr = <intptr_t>(slicer.get_ptr())
884
+ if grid_shape is None:
885
+ if slicer.is_squeezed:
886
+ grid_shape = np.array([len(f) for f in slicer.filtration_grid])
887
+ else:
888
+ grid_shape = (slicer.filtration_bounds()[1]).astype(python_indices_type)+1
889
+ grid_shape = np.asarray(grid_shape)
890
+
891
+ cdef int num_parameters = len(grid_shape)
892
+
893
+ if zero_pad:
894
+ for i, _ in enumerate(grid_shape):
895
+ grid_shape[i] += 1 # adds a 0
896
+ # for i,f in enumerate(grid_conversion):
897
+ # grid_conversion[i] = np.concatenate([f, [mass_default[i]]])
898
+
899
+ grid_shape_with_degree = np.asarray(np.concatenate([[len(degrees)], grid_shape, grid_shape]), dtype=python_indices_type)
900
+ container_array = np.ascontiguousarray(np.zeros(grid_shape_with_degree, dtype=python_tensor_dtype).ravel())
901
+ assert len(container_array) < np.iinfo(python_indices_type).max, "Too large container. Raise an issue on github if you encounter this issue. (Due to tensor's operator[])"
902
+ cdef vector[indices_type] c_grid_shape = grid_shape_with_degree
903
+ cdef tensor_dtype[::1] container = container_array
904
+ cdef tensor_dtype* container_ptr = &container[0]
905
+
906
+ ## SLICERS
907
+ _compute_rank_invariant(slicer, container_ptr, c_grid_shape, degrees, n_jobs, ignore_inf)
908
+
909
+ rank = container_array.reshape(grid_shape_with_degree)
910
+ rank = tuple(rank_decomposition_by_rectangles(rank_of_degree, threshold = zero_pad) for rank_of_degree in rank)
911
+ if return_raw:
912
+ return rank
913
+ out = []
914
+ def clean_rank(rank_decomposition):
915
+ (coords, weights) = sparsify(np.ascontiguousarray(rank_decomposition))
916
+ births = coords[:,:num_parameters]
917
+ deaths = coords[:,num_parameters:]
918
+ correct_indices = np.all(births<=deaths, axis=1)
919
+ coords = coords[correct_indices]
920
+ weights = weights[correct_indices]
921
+ return coords, weights
922
+
923
+ out = tuple(clean_rank(rank_decomposition) for rank_decomposition in rank)
924
+ return out