multipers 2.3.1__cp313-cp313-macosx_13_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.

Potentially problematic release.


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

Files changed (180) hide show
  1. multipers/.dylibs/libc++.1.0.dylib +0 -0
  2. multipers/.dylibs/libtbb.12.14.dylib +0 -0
  3. multipers/__init__.py +33 -0
  4. multipers/_signed_measure_meta.py +430 -0
  5. multipers/_slicer_meta.py +211 -0
  6. multipers/data/MOL2.py +458 -0
  7. multipers/data/UCR.py +18 -0
  8. multipers/data/__init__.py +1 -0
  9. multipers/data/graphs.py +466 -0
  10. multipers/data/immuno_regions.py +27 -0
  11. multipers/data/minimal_presentation_to_st_bf.py +0 -0
  12. multipers/data/pytorch2simplextree.py +91 -0
  13. multipers/data/shape3d.py +101 -0
  14. multipers/data/synthetic.py +113 -0
  15. multipers/distances.py +198 -0
  16. multipers/filtration_conversions.pxd +229 -0
  17. multipers/filtration_conversions.pxd.tp +84 -0
  18. multipers/filtrations/__init__.py +18 -0
  19. multipers/filtrations/density.py +563 -0
  20. multipers/filtrations/filtrations.py +289 -0
  21. multipers/filtrations.pxd +224 -0
  22. multipers/function_rips.cpython-313-darwin.so +0 -0
  23. multipers/function_rips.pyx +105 -0
  24. multipers/grids.cpython-313-darwin.so +0 -0
  25. multipers/grids.pyx +350 -0
  26. multipers/gudhi/Persistence_slices_interface.h +132 -0
  27. multipers/gudhi/Simplex_tree_interface.h +239 -0
  28. multipers/gudhi/Simplex_tree_multi_interface.h +516 -0
  29. multipers/gudhi/cubical_to_boundary.h +59 -0
  30. multipers/gudhi/gudhi/Bitmap_cubical_complex.h +450 -0
  31. multipers/gudhi/gudhi/Bitmap_cubical_complex_base.h +1070 -0
  32. multipers/gudhi/gudhi/Bitmap_cubical_complex_periodic_boundary_conditions_base.h +579 -0
  33. multipers/gudhi/gudhi/Debug_utils.h +45 -0
  34. multipers/gudhi/gudhi/Fields/Multi_field.h +484 -0
  35. multipers/gudhi/gudhi/Fields/Multi_field_operators.h +455 -0
  36. multipers/gudhi/gudhi/Fields/Multi_field_shared.h +450 -0
  37. multipers/gudhi/gudhi/Fields/Multi_field_small.h +531 -0
  38. multipers/gudhi/gudhi/Fields/Multi_field_small_operators.h +507 -0
  39. multipers/gudhi/gudhi/Fields/Multi_field_small_shared.h +531 -0
  40. multipers/gudhi/gudhi/Fields/Z2_field.h +355 -0
  41. multipers/gudhi/gudhi/Fields/Z2_field_operators.h +376 -0
  42. multipers/gudhi/gudhi/Fields/Zp_field.h +420 -0
  43. multipers/gudhi/gudhi/Fields/Zp_field_operators.h +400 -0
  44. multipers/gudhi/gudhi/Fields/Zp_field_shared.h +418 -0
  45. multipers/gudhi/gudhi/Flag_complex_edge_collapser.h +337 -0
  46. multipers/gudhi/gudhi/Matrix.h +2107 -0
  47. multipers/gudhi/gudhi/Multi_critical_filtration.h +1038 -0
  48. multipers/gudhi/gudhi/Multi_persistence/Box.h +171 -0
  49. multipers/gudhi/gudhi/Multi_persistence/Line.h +282 -0
  50. multipers/gudhi/gudhi/Off_reader.h +173 -0
  51. multipers/gudhi/gudhi/One_critical_filtration.h +1433 -0
  52. multipers/gudhi/gudhi/Persistence_matrix/Base_matrix.h +769 -0
  53. multipers/gudhi/gudhi/Persistence_matrix/Base_matrix_with_column_compression.h +686 -0
  54. multipers/gudhi/gudhi/Persistence_matrix/Boundary_matrix.h +842 -0
  55. multipers/gudhi/gudhi/Persistence_matrix/Chain_matrix.h +1350 -0
  56. multipers/gudhi/gudhi/Persistence_matrix/Id_to_index_overlay.h +1105 -0
  57. multipers/gudhi/gudhi/Persistence_matrix/Position_to_index_overlay.h +859 -0
  58. multipers/gudhi/gudhi/Persistence_matrix/RU_matrix.h +910 -0
  59. multipers/gudhi/gudhi/Persistence_matrix/allocators/entry_constructors.h +139 -0
  60. multipers/gudhi/gudhi/Persistence_matrix/base_pairing.h +230 -0
  61. multipers/gudhi/gudhi/Persistence_matrix/base_swap.h +211 -0
  62. multipers/gudhi/gudhi/Persistence_matrix/boundary_cell_position_to_id_mapper.h +60 -0
  63. multipers/gudhi/gudhi/Persistence_matrix/boundary_face_position_to_id_mapper.h +60 -0
  64. multipers/gudhi/gudhi/Persistence_matrix/chain_pairing.h +136 -0
  65. multipers/gudhi/gudhi/Persistence_matrix/chain_rep_cycles.h +190 -0
  66. multipers/gudhi/gudhi/Persistence_matrix/chain_vine_swap.h +616 -0
  67. multipers/gudhi/gudhi/Persistence_matrix/columns/chain_column_extra_properties.h +150 -0
  68. multipers/gudhi/gudhi/Persistence_matrix/columns/column_dimension_holder.h +106 -0
  69. multipers/gudhi/gudhi/Persistence_matrix/columns/column_utilities.h +219 -0
  70. multipers/gudhi/gudhi/Persistence_matrix/columns/entry_types.h +327 -0
  71. multipers/gudhi/gudhi/Persistence_matrix/columns/heap_column.h +1140 -0
  72. multipers/gudhi/gudhi/Persistence_matrix/columns/intrusive_list_column.h +934 -0
  73. multipers/gudhi/gudhi/Persistence_matrix/columns/intrusive_set_column.h +934 -0
  74. multipers/gudhi/gudhi/Persistence_matrix/columns/list_column.h +980 -0
  75. multipers/gudhi/gudhi/Persistence_matrix/columns/naive_vector_column.h +1092 -0
  76. multipers/gudhi/gudhi/Persistence_matrix/columns/row_access.h +192 -0
  77. multipers/gudhi/gudhi/Persistence_matrix/columns/set_column.h +921 -0
  78. multipers/gudhi/gudhi/Persistence_matrix/columns/small_vector_column.h +1093 -0
  79. multipers/gudhi/gudhi/Persistence_matrix/columns/unordered_set_column.h +1012 -0
  80. multipers/gudhi/gudhi/Persistence_matrix/columns/vector_column.h +1244 -0
  81. multipers/gudhi/gudhi/Persistence_matrix/matrix_dimension_holders.h +186 -0
  82. multipers/gudhi/gudhi/Persistence_matrix/matrix_row_access.h +164 -0
  83. multipers/gudhi/gudhi/Persistence_matrix/ru_pairing.h +156 -0
  84. multipers/gudhi/gudhi/Persistence_matrix/ru_rep_cycles.h +376 -0
  85. multipers/gudhi/gudhi/Persistence_matrix/ru_vine_swap.h +540 -0
  86. multipers/gudhi/gudhi/Persistent_cohomology/Field_Zp.h +118 -0
  87. multipers/gudhi/gudhi/Persistent_cohomology/Multi_field.h +173 -0
  88. multipers/gudhi/gudhi/Persistent_cohomology/Persistent_cohomology_column.h +128 -0
  89. multipers/gudhi/gudhi/Persistent_cohomology.h +745 -0
  90. multipers/gudhi/gudhi/Points_off_io.h +171 -0
  91. multipers/gudhi/gudhi/Simple_object_pool.h +69 -0
  92. multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_iterators.h +463 -0
  93. multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_node_explicit_storage.h +83 -0
  94. multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_siblings.h +106 -0
  95. multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_star_simplex_iterators.h +277 -0
  96. multipers/gudhi/gudhi/Simplex_tree/hooks_simplex_base.h +62 -0
  97. multipers/gudhi/gudhi/Simplex_tree/indexing_tag.h +27 -0
  98. multipers/gudhi/gudhi/Simplex_tree/serialization_utils.h +62 -0
  99. multipers/gudhi/gudhi/Simplex_tree/simplex_tree_options.h +157 -0
  100. multipers/gudhi/gudhi/Simplex_tree.h +2794 -0
  101. multipers/gudhi/gudhi/Simplex_tree_multi.h +152 -0
  102. multipers/gudhi/gudhi/distance_functions.h +62 -0
  103. multipers/gudhi/gudhi/graph_simplicial_complex.h +104 -0
  104. multipers/gudhi/gudhi/persistence_interval.h +253 -0
  105. multipers/gudhi/gudhi/persistence_matrix_options.h +170 -0
  106. multipers/gudhi/gudhi/reader_utils.h +367 -0
  107. multipers/gudhi/mma_interface_coh.h +256 -0
  108. multipers/gudhi/mma_interface_h0.h +223 -0
  109. multipers/gudhi/mma_interface_matrix.h +291 -0
  110. multipers/gudhi/naive_merge_tree.h +536 -0
  111. multipers/gudhi/scc_io.h +310 -0
  112. multipers/gudhi/truc.h +957 -0
  113. multipers/io.cpython-313-darwin.so +0 -0
  114. multipers/io.pyx +714 -0
  115. multipers/ml/__init__.py +0 -0
  116. multipers/ml/accuracies.py +90 -0
  117. multipers/ml/invariants_with_persistable.py +79 -0
  118. multipers/ml/kernels.py +176 -0
  119. multipers/ml/mma.py +713 -0
  120. multipers/ml/one.py +472 -0
  121. multipers/ml/point_clouds.py +352 -0
  122. multipers/ml/signed_measures.py +1589 -0
  123. multipers/ml/sliced_wasserstein.py +461 -0
  124. multipers/ml/tools.py +113 -0
  125. multipers/mma_structures.cpython-313-darwin.so +0 -0
  126. multipers/mma_structures.pxd +127 -0
  127. multipers/mma_structures.pyx +2742 -0
  128. multipers/mma_structures.pyx.tp +1083 -0
  129. multipers/multi_parameter_rank_invariant/diff_helpers.h +84 -0
  130. multipers/multi_parameter_rank_invariant/euler_characteristic.h +97 -0
  131. multipers/multi_parameter_rank_invariant/function_rips.h +322 -0
  132. multipers/multi_parameter_rank_invariant/hilbert_function.h +769 -0
  133. multipers/multi_parameter_rank_invariant/persistence_slices.h +148 -0
  134. multipers/multi_parameter_rank_invariant/rank_invariant.h +369 -0
  135. multipers/multiparameter_edge_collapse.py +41 -0
  136. multipers/multiparameter_module_approximation/approximation.h +2298 -0
  137. multipers/multiparameter_module_approximation/combinatory.h +129 -0
  138. multipers/multiparameter_module_approximation/debug.h +107 -0
  139. multipers/multiparameter_module_approximation/euler_curves.h +0 -0
  140. multipers/multiparameter_module_approximation/format_python-cpp.h +286 -0
  141. multipers/multiparameter_module_approximation/heap_column.h +238 -0
  142. multipers/multiparameter_module_approximation/images.h +79 -0
  143. multipers/multiparameter_module_approximation/list_column.h +174 -0
  144. multipers/multiparameter_module_approximation/list_column_2.h +232 -0
  145. multipers/multiparameter_module_approximation/ru_matrix.h +347 -0
  146. multipers/multiparameter_module_approximation/set_column.h +135 -0
  147. multipers/multiparameter_module_approximation/structure_higher_dim_barcode.h +36 -0
  148. multipers/multiparameter_module_approximation/unordered_set_column.h +166 -0
  149. multipers/multiparameter_module_approximation/utilities.h +403 -0
  150. multipers/multiparameter_module_approximation/vector_column.h +223 -0
  151. multipers/multiparameter_module_approximation/vector_matrix.h +331 -0
  152. multipers/multiparameter_module_approximation/vineyards.h +464 -0
  153. multipers/multiparameter_module_approximation/vineyards_trajectories.h +649 -0
  154. multipers/multiparameter_module_approximation.cpython-313-darwin.so +0 -0
  155. multipers/multiparameter_module_approximation.pyx +218 -0
  156. multipers/pickle.py +90 -0
  157. multipers/plots.py +342 -0
  158. multipers/point_measure.cpython-313-darwin.so +0 -0
  159. multipers/point_measure.pyx +322 -0
  160. multipers/simplex_tree_multi.cpython-313-darwin.so +0 -0
  161. multipers/simplex_tree_multi.pxd +133 -0
  162. multipers/simplex_tree_multi.pyx +10402 -0
  163. multipers/simplex_tree_multi.pyx.tp +1947 -0
  164. multipers/slicer.cpython-313-darwin.so +0 -0
  165. multipers/slicer.pxd +2552 -0
  166. multipers/slicer.pxd.tp +218 -0
  167. multipers/slicer.pyx +16530 -0
  168. multipers/slicer.pyx.tp +931 -0
  169. multipers/tensor/tensor.h +672 -0
  170. multipers/tensor.pxd +13 -0
  171. multipers/test.pyx +44 -0
  172. multipers/tests/__init__.py +57 -0
  173. multipers/torch/__init__.py +1 -0
  174. multipers/torch/diff_grids.py +217 -0
  175. multipers/torch/rips_density.py +310 -0
  176. multipers-2.3.1.dist-info/LICENSE +21 -0
  177. multipers-2.3.1.dist-info/METADATA +144 -0
  178. multipers-2.3.1.dist-info/RECORD +180 -0
  179. multipers-2.3.1.dist-info/WHEEL +6 -0
  180. multipers-2.3.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2742 @@
1
+
2
+
3
+
4
+
5
+
6
+ """!
7
+ @package mma
8
+ @brief Files containing the C++ cythonized functions.
9
+ @author David Loiseaux
10
+ @copyright Copyright (c) 2022 Inria.
11
+ """
12
+
13
+ # distutils: language = c++
14
+
15
+ ###########################################################################
16
+ ## PYTHON LIBRARIES
17
+ import gudhi as gd
18
+ import numpy as np
19
+ from typing import Union, Literal
20
+ from collections.abc import Callable, Iterable, Sequence
21
+ import pickle
22
+ import multipers.grids as mpg
23
+
24
+ ###########################################################################
25
+ ## CPP CLASSES
26
+ from libc.stdint cimport intptr_t
27
+ from libc.stdint cimport uintptr_t
28
+
29
+ ###########################################################################
30
+ ## CYTHON TYPES
31
+ from libcpp.vector cimport vector
32
+ from libcpp.utility cimport pair
33
+ #from libcpp.list cimport list as clist
34
+ from libcpp cimport bool
35
+ from libcpp cimport int
36
+ from cython.operator cimport dereference
37
+ from libcpp.utility cimport move
38
+ cimport cython
39
+ #########################################################################
40
+ ## Multipersistence Module Approximation Classes
41
+ from multipers.mma_structures cimport *
42
+ from multipers.filtration_conversions cimport *
43
+ cimport numpy as cnp
44
+
45
+
46
+ #########################################################################
47
+ ## Small hack for typing
48
+ from gudhi import SimplexTree
49
+ from multipers.simplex_tree_multi import SimplexTreeMulti
50
+ from joblib import Parallel, delayed
51
+
52
+ available_pymodules = [
53
+ PyModule_f64,
54
+ PyModule_f32,
55
+ PyModule_i32,
56
+ PyModule_i64,
57
+ ]
58
+
59
+ PyModule_type = Union[
60
+ PyModule_f64,
61
+ PyModule_f32,
62
+ PyModule_i32,
63
+ PyModule_i64,
64
+ ]
65
+ cdef class PySummand_f64:
66
+ r"""
67
+ Stores a Summand of a PyModule
68
+ """
69
+ cdef Summand[double] sum
70
+
71
+ def get_birth_list(self):
72
+ cdef vector[One_critical_filtration[double]] v = self.sum.get_birth_list()
73
+ return _vff21cview_f64(v, copy = True, duplicate = self.num_parameters())
74
+
75
+ def get_death_list(self):
76
+ cdef vector[One_critical_filtration[double]] v = self.sum.get_death_list()
77
+ return _vff21cview_f64(v, copy = True, duplicate = self.num_parameters())
78
+ @property
79
+ def degree(self)->int:
80
+ return self.sum.get_dimension()
81
+
82
+ cdef set(self, Summand[double]& summand):
83
+ self.sum = summand
84
+ return self
85
+ def get_bounds(self):
86
+ cdef pair[One_critical_filtration[double],One_critical_filtration[double]] cbounds
87
+ with nogil:
88
+ cbounds = self.sum.get_bounds().get_bounding_corners()
89
+ return _ff21cview_f64(&cbounds.first).copy(), _ff21cview_f64(&cbounds.second).copy()
90
+ @property
91
+ def dtype(self):
92
+ return np.float64
93
+
94
+ def num_parameters(self):
95
+ cdef vector[One_critical_filtration[double]] v = self.sum.get_birth_list()
96
+ if v[0].is_finite():
97
+ return v[0].num_parameters()
98
+ v = self.sum.get_death_list()
99
+ return v[0].num_parameters()
100
+
101
+ cdef inline get_summand_filtration_values_f64(Summand[double] summand):
102
+ r"""
103
+ Returns a list (over parameter) of the filtrations values of this parameter.
104
+ """
105
+ cdef vector[One_critical_filtration[double]] vb = summand.get_birth_list()
106
+ cdef vector[One_critical_filtration[double]] vd = summand.get_death_list()
107
+
108
+ if vb[0].is_finite():
109
+ if vd[0].is_finite():
110
+ pts = np.concatenate([_vff21cview_f64(vb, copy=True),
111
+ _vff21cview_f64(vd, copy=True)],axis=0)
112
+ else:
113
+ pts = np.array(_vff21cview_f64(vb, copy=True))
114
+ else:
115
+ if vd[0].is_finite():
116
+ pts = np.array(_vff21cview_f64(vd, copy=True))
117
+ else:
118
+ return []
119
+
120
+ num_parameters = pts.shape[1]
121
+ out = [np.unique(pts[:,parameter]) for parameter in range(num_parameters)]
122
+ out = [f[:-1] if f[-1] == np.inf else f for f in out]
123
+ out = [f[1:] if f[0] == -np.inf else f for f in out]
124
+ return out
125
+
126
+ cdef class PyBox_f64:
127
+ cdef Box[double] box
128
+ def __cinit__(self, vector[double]& bottomCorner, vector[double]& topCorner):
129
+ self.box = Box[double](bottomCorner, topCorner)
130
+ @property
131
+ def num_parameters(self):
132
+ cdef size_t dim = self.box.get_lower_corner().num_parameters()
133
+ if dim == self.box.get_upper_corner().num_parameters(): return dim
134
+ else: print("Bad box definition.")
135
+ def contains(self, x):
136
+ return self.box.contains(x)
137
+ cdef set(self, Box[double]& b):
138
+ self.box = b
139
+ return self
140
+
141
+ def get(self):
142
+ return [<vector[double]>self.box.get_lower_corner(), <vector[double]>self.box.get_upper_corner()]
143
+ def to_multipers(self):
144
+ #assert (self.get_dimension() == 2) "Multipers only works in dimension 2 !"
145
+ return np.array(self.get()).flatten(order = 'F')
146
+ @property
147
+ def dtype(self):
148
+ return np.float64
149
+
150
+
151
+
152
+ cdef class PyModule_f64:
153
+ r"""
154
+ Stores a representation of a n-persistence module.
155
+ """
156
+ cdef Module[double] cmod
157
+
158
+ @property
159
+ def dtype(self):
160
+ return np.float64
161
+
162
+ cdef set(self, Module[double] m):
163
+ self.cmod = m
164
+ def merge(self, PyModule_f64 other, int dim=-1):
165
+ r"""
166
+ Merges two modules into one
167
+ """
168
+ cdef Module[double] c_other = other.cmod
169
+ with nogil:
170
+ for summand in c_other:
171
+ self.cmod.add_summand(summand, dim)
172
+ return self
173
+
174
+ def _set_from_ptr(self, intptr_t module_ptr):
175
+ r"""
176
+ Copy module from a memory pointer. Unsafe.
177
+ """
178
+ self.cmod = move(dereference(<Module[double]*>(module_ptr)))
179
+ def set_box(self, PyBox_f64 pybox):
180
+ cdef Box[double] cbox = pybox.box
181
+ with nogil:
182
+ self.cmod.set_box(cbox)
183
+ return self
184
+ def get_module_of_degree(self, int degree)->PyModule_f64: # TODO : in c++ ?
185
+ r"""
186
+ Returns a copy of a module of fixed degree.
187
+ """
188
+ pmodule = PyModule_f64()
189
+ cdef Box[double] c_box = self.cmod.get_box()
190
+ pmodule.cmod.set_box(c_box)
191
+ with nogil:
192
+ for summand in self.cmod:
193
+ if summand.get_dimension() == degree:
194
+ pmodule.cmod.add_summand(summand)
195
+ return pmodule
196
+ def get_module_of_degrees(self, degrees:Iterable[int])->PyModule_f64: # TODO : in c++ ?
197
+ r"""
198
+ Returns a copy of the summands of degrees in `degrees`
199
+ """
200
+ pmodule = PyModule_f64()
201
+ cdef Box[double] c_box = self.cmod.get_box()
202
+ pmodule.cmod.set_box(c_box)
203
+ cdef vector[int] cdegrees = degrees
204
+ with nogil:
205
+ for summand in self.cmod:
206
+ for d in cdegrees:
207
+ if d == summand.get_dimension():
208
+ pmodule.cmod.add_summand(summand)
209
+ return pmodule
210
+ def __len__(self)->int:
211
+ return self.cmod.size()
212
+ def get_bottom(self)->np.ndarray:
213
+ r"""
214
+ Bottom of the box of the module
215
+ """
216
+ return np.asarray(<vector[double]>(self.cmod.get_box().get_lower_corner()))
217
+ def get_top(self)->np.ndarray:
218
+ r"""
219
+ Top of the box of the module
220
+ """
221
+ return np.asarray(<vector[double]>(self.cmod.get_box().get_upper_corner()))
222
+ def get_box(self)->np.ndarray:
223
+ r"""
224
+ Returns the current bounding box of the module.
225
+ """
226
+ return np.asarray([self.get_bottom(), self.get_top()])
227
+ @property
228
+ def max_degree(self)->int:
229
+ r"""
230
+ Returns the maximum degree of the module.
231
+ """
232
+ return self.cmod.get_dimension()
233
+ @property
234
+ def num_parameters(self)->int:
235
+ cdef size_t dim = self.cmod.get_box().get_lower_corner().num_parameters()
236
+ assert dim == self.cmod.get_box().get_upper_corner().num_parameters(), "Bad box definition, cannot infer num_parameters."
237
+ return dim
238
+ def dump(self, path:str|None=None):
239
+ r"""
240
+ Dumps the module into a pickle-able format.
241
+
242
+ Parameters
243
+ ----------
244
+
245
+ path:str=None (optional) saves the pickled module in specified path
246
+
247
+ Returns
248
+ -------
249
+
250
+ list of list, encoding the module, which can be retrieved with the function `from_dump`.
251
+ """
252
+ ## TODO : optimize, but not really used.
253
+ return dump_cmod_f64(self.cmod)
254
+ def __getstate__(self):
255
+ return self.dump()
256
+ def __setstate__(self,dump):
257
+ cdef Module[double] cmod = cmod_from_dump_f64(dump)
258
+ self.cmod = cmod
259
+ return
260
+ def __getitem__(self, int i) -> PySummand_f64:
261
+ if i == slice(None):
262
+ return self
263
+ summand = PySummand_f64()
264
+ summand.set(self.cmod.at(i % self.cmod.size()))
265
+ return summand
266
+ def __iter__(self):
267
+ cdef int num_summands = self.cmod.size()
268
+ for i in range(num_summands):
269
+ summand = PySummand_f64()
270
+ summand.set(self.cmod.at(i)) ## hmm copy. maybe do summand from ptr
271
+ yield summand
272
+
273
+ def get_bounds(self):
274
+ r"""
275
+ Computes bounds from the summands' bounds.
276
+ Useful to change this' box.
277
+ """
278
+ cdef pair[One_critical_filtration[double],One_critical_filtration[double]] cbounds
279
+ with nogil:
280
+ cbounds = self.cmod.get_bounds().get_bounding_corners()
281
+ return _ff21cview_f64(&cbounds.first).copy(), _ff21cview_f64(&cbounds.second).copy()
282
+ def rescale(self,rescale_factors, int degree=-1):
283
+ r"""
284
+ Rescales the fitlration values of the summands by this rescaling vector.
285
+ """
286
+ cdef vector[double] crescale_factors = rescale_factors
287
+ with nogil:
288
+ self.cmod.rescale(crescale_factors,degree)
289
+ def translate(self,translation, int degree=-1):
290
+ r"""
291
+ Translates the module in the filtration space by this vector.
292
+ """
293
+ cdef vector[double] ctranslation = translation
294
+ with nogil:
295
+ self.cmod.translate(ctranslation,degree)
296
+
297
+ def get_filtration_values(self, bool unique=True):
298
+ r"""
299
+ Retrieves all filtration values of the summands of the module.
300
+
301
+ Output format
302
+ -------------
303
+
304
+ list of filtration values for parameter.
305
+ """
306
+ if len(self) ==0:
307
+ return np.empty((self.num_parameters,0))
308
+ values = tuple(tuple(stuff) if len(stuff:=get_summand_filtration_values_f64(summand)) == self.num_parameters else list(stuff) + [[]]*(self.num_parameters - len(stuff)) for summand in self.cmod)
309
+ try:
310
+ values = tuple(np.concatenate([
311
+ f[parameter]
312
+ for f in values
313
+ ], axis=0) for parameter in range(self.num_parameters)
314
+ )
315
+ except:
316
+ return values
317
+ if unique:
318
+ return [np.unique(f) for f in values]
319
+ return values
320
+
321
+ def plot(self, int degree=-1,**kwargs)->None:
322
+ r"""Shows the module on a plot. Each color corresponds to an apprimation summand of the module, and its shape corresponds to its support.
323
+ Only works with 2-parameter modules.
324
+
325
+ Parameters
326
+ ----------
327
+ degree = -1 : integer
328
+ If positive returns only the image of dimension `dimension`.
329
+ box=None : of the form [[b_x,b_y], [d_x,d_y]] where b,d are the bottom and top corner of the rectangle.
330
+ If non-None, will plot the module on this specific rectangle.
331
+ min_persistence =0 : float
332
+ Only plots the summand with a persistence above this threshold.
333
+ separated=False : bool
334
+ If true, plot each summand in a different plot.
335
+ alpha=1 : float
336
+ Transparancy parameter
337
+ save = False : string
338
+ if nontrivial, will save the figure at this path
339
+
340
+
341
+ Returns
342
+ -------
343
+ The figure of the plot.
344
+ """
345
+ from multipers.plots import plot2d_PyModule
346
+ import matplotlib.pyplot as plt
347
+ box = kwargs.pop('box', self.get_box())
348
+ if (len(box[0]) != 2):
349
+ print("Filtration size :", len(box[0]), " != 2")
350
+ return
351
+ if(degree < 0):
352
+ dims = np.unique(self.get_dimensions())
353
+ separated = kwargs.pop("separated", False)
354
+ ndim = len(dims)
355
+ scale = kwargs.pop("scale", 4)
356
+ if separated:
357
+ fig = None
358
+ axes = None
359
+ elif ndim > 1:
360
+ fig, axes = plt.subplots(1,ndim, figsize=(ndim*scale,scale))
361
+ else:
362
+ fig = plt.gcf()
363
+ axes = [plt.gca()]
364
+ for dim_idx in range(ndim):
365
+ if not separated:
366
+ plt.sca(axes[dim_idx])
367
+ self.plot(dims[dim_idx],box=box, separated = separated, **kwargs)
368
+ return
369
+ corners = self.cmod.get_corners_of_dimension(degree)
370
+ plot2d_PyModule(corners, box=box, dimension=degree, **kwargs)
371
+ return
372
+ def degree_splits(self):
373
+ return np.asarray(self.cmod.get_degree_splits(), dtype=np.int64)
374
+ def _compute_pixels(self,coordinates:np.ndarray,
375
+ degrees=None, box=None, double delta=.1,
376
+ double p=1., bool normalize=False, int n_jobs=0):
377
+ r"""
378
+ Computes the image of the module at the given coordinates
379
+ """
380
+ if degrees is not None: assert np.all(degrees[:-1] <= degrees[1:]), "Degrees have to be sorted"
381
+ cdef vector[int] cdegrees = np.arange(self.max_degree +1) if degrees is None else degrees
382
+ pybox = PyBox_f64(*self.get_box()) if box is None else PyBox_f64(*box)
383
+ cdef Box[double] cbox = pybox.box
384
+ cdef vector[vector[double]] ccoords = coordinates
385
+ cdef vector[vector[double]] out
386
+ with nogil:
387
+ out = self.cmod.compute_pixels(ccoords, cdegrees, cbox, delta, p, normalize, n_jobs)
388
+ return np.asarray(out)
389
+ def barcode(self, basepoint, int degree = -1,*, bool threshold = False): # TODO direction vector interface
390
+ r"""Computes the barcode of module along a lines.
391
+
392
+ Parameters
393
+ ----------
394
+
395
+ basepoint : vector
396
+ basepoint of the lines on which to compute the barcodes, i.e. a point on the line
397
+ degree = -1 : integer
398
+ Homology degree on which to compute the bars. If negative, every dimension is computed
399
+ box (default) :
400
+ box on which to compute the barcodes if basepoints is not specified. Default is a linspace of lines crossing that box.
401
+ threshold = False :
402
+ Thre
403
+
404
+ Warning
405
+ -------
406
+
407
+ If the barcodes are not thresholded, essential barcodes will not be plot-able.
408
+
409
+ Returns
410
+ -------
411
+
412
+ PyMultiDiagrams
413
+ Structure that holds the barcodes. Barcodes can be retrieved with a .get_points() or a .to_multipers() or a .plot().
414
+ """
415
+ out = PyMultiDiagram_f64()
416
+ out.set(self.cmod.get_barcode(Line[double](_py21c_f64(np.asarray(basepoint, dtype=np.float64))), degree, threshold))
417
+ return out
418
+ @staticmethod
419
+ cdef _threshold_bc(bc):
420
+ return tuple(np.fromiter((a for a in stuff if a[0] < np.inf), dtype=np.dtype((np.float64,2)) ) for stuff in bc)
421
+ @staticmethod
422
+ def _bc_to_full(bcs, basepoint, direction=None):
423
+ # i, (b sv d), coords
424
+ basepoint = np.asarray(basepoint)[None,None,:]
425
+ direction = 1 if direction is None else np.asarray(direction)[None,None,:]
426
+ return tuple(bc[:,:,None]*direction + basepoint for bc in bcs)
427
+ def barcode2(self, basepoint, direction=None, int degree = -1,*, bool threshold = False, bool keep_inf = True, bool full = False): # TODO direction vector interface
428
+ r"""
429
+ Compute the 1d-barcode a diagonal line based on basepoint, with some direction.
430
+
431
+ Parameters
432
+ ----------
433
+
434
+ - basepoint: 1d array
435
+ - directiont: 1d array or None, if None: diagonal
436
+ - degree: int the degree to compute (-1 means all)
437
+ - threshold: bool if True, threshold the barcode to the modules box
438
+ - keep_inf: bool if False, removes trivial bars
439
+ Note that this removes the order w.r.t. the summands in that case
440
+ - full:bool if True, returns the coordinates of the barcode instead of the coordinate in the line.
441
+
442
+ The output is of the form
443
+
444
+ tuple[np.ndarray of shape (num_bars,2)] or tuple[array of shape (num_bar, 2, num_parameters)]
445
+ """
446
+ basepoint = np.asarray(basepoint, dtype=np.float64)
447
+ if direction is None:
448
+ bc = tuple(np.asarray(x).reshape(-1,2) for x in self.cmod.get_barcode2(Line[double](_py21c_f64(basepoint)), degree))
449
+ else:
450
+ direction = np.asarray(direction, dtype = np.float64)
451
+ bc = tuple(np.asarray(x).reshape(-1,2) for x in self.cmod.get_barcode2(Line[double](_py21c_f64(basepoint), _py21c_f64(direction)), degree))
452
+ if not keep_inf:
453
+ bc = PyModule_f64._threshold_bc(bc)
454
+ if full:
455
+ bc = PyModule_f64._bc_to_full(bc, basepoint, direction)
456
+
457
+ return bc
458
+
459
+ def get_dimensions(self):
460
+ cdef int num_summands = len(self)
461
+ out = np.empty(shape=num_summands, dtype=np.int32)
462
+ cdef int32_t[:] c_out = out
463
+ for i in range(num_summands):
464
+ c_out[i] = self.cmod.at(i).get_dimension()
465
+ return out
466
+
467
+ def barcodes(self, int degree, basepoints = None, num=100, box = None,threshold = False):
468
+ r"""Computes barcodes of module along a set of lines.
469
+
470
+ Parameters
471
+ ----------
472
+
473
+ basepoints = None : list of vectors
474
+ basepoints of the lines on which to compute the barcodes.
475
+ degree = -1 : integer
476
+ Homology degree on which to compute the bars. If negative, every dimension is computed
477
+ box (default) :
478
+ box on which to compute the barcodes if basepoints is not specified. Default is a linspace of lines crossing that box.
479
+ num:int=100
480
+ if basepoints is not specified, defines the number of lines to consider.
481
+ threshold = False : threshold t
482
+ Resolution of the image(s).
483
+
484
+ Warning
485
+ -------
486
+
487
+ If the barcodes are not thresholded, essential barcodes will not be plot-able.
488
+
489
+ Returns
490
+ -------
491
+
492
+ PyMultiDiagrams
493
+ Structure that holds the barcodes. Barcodes can be retrieved with a .get_points() or a .to_multipers() or a .plot().
494
+ """
495
+ out = PyMultiDiagrams_f64()
496
+ if box is None:
497
+ box = [self.get_bottom(), self.get_top()]
498
+ if (len(box[0]) != 2) and (basepoints is None):
499
+ raise ValueError("Basepoints has to be specified for filtration dimension >= 3 !")
500
+ elif basepoints is None:
501
+ h = box[1][1] - box[0][1]
502
+ basepoints = np.linspace([box[0][0] - h,box[0][1]], [box[1][0],box[0][1]], num=num)
503
+ else :
504
+ num=len(basepoints)
505
+
506
+ cdef double[:,:] basepoints_view = np.asarray(basepoints, dtype = np.float64)
507
+ cdef vector[One_critical_filtration[double]] cbasepoints = _py2v1c_f64(basepoints_view)
508
+
509
+ out.set(self.cmod.get_barcodes(cbasepoints, degree, threshold))
510
+ return out
511
+
512
+ def barcodes2(self, int degree = -1, basepoints = None, int num=100, box = None, bool threshold = False):
513
+ r"""Computes barcodes of module along a set of lines.
514
+
515
+ Parameters
516
+ ----------
517
+
518
+ basepoints = None : list of vectors
519
+ basepoints of the lines on which to compute the barcodes.
520
+ degree = -1 : integer
521
+ Homology degree on which to compute the bars. If negative, every dimension is computed
522
+ box (default) :
523
+ box on which to compute the barcodes if basepoints is not specified. Default is a linspace of lines crossing that box.
524
+ num:int=100
525
+ if basepoints is not specified, defines the number of lines to consider.
526
+ threshold = False : threshold t
527
+ Resolution of the image(s).
528
+
529
+ Warning
530
+ -------
531
+
532
+ If the barcodes are not thresholded, essential barcodes will not be plot-able.
533
+
534
+ Returns
535
+ -------
536
+
537
+ tuple of 1d barcodes, based on basepoint, with direction (1,1)
538
+ """
539
+ if box is None:
540
+ box = [self.get_bottom(), self.get_top()]
541
+ if (len(box[0]) != 2) and (basepoints is None):
542
+ raise ValueError("Basepoints has to be specified for filtration dimension >= 3 !")
543
+ elif basepoints is None:
544
+ h = box[1][1] - box[0][1]
545
+ basepoints = np.linspace([box[0][0] - h,box[0][1]], [box[1][0],box[0][1]], num=num)
546
+ else :
547
+ num=len(basepoints)
548
+
549
+ basepoints = np.asarray(basepoints, dtype=np.float64)
550
+ cdef vector[Line[double]] cbasepoints
551
+ for i in range(num):
552
+ cbasepoints.push_back(Line[double](_py21c_f64(basepoints[i])))
553
+ return tuple(np.asarray(bc) for bc in self.cmod.get_barcodes2(cbasepoints, degree))
554
+
555
+ def landscape(self, degree:int, k:int=0,box:Sequence|np.ndarray|None=None, resolution:Sequence=[100,100], bool plot=False):
556
+ r"""Computes the multiparameter landscape from a PyModule. Python interface only bifiltrations.
557
+
558
+ Parameters
559
+ ----------
560
+
561
+ degree : integer
562
+ The homology degree of the landscape.
563
+ k = 0 : int
564
+ the k-th landscape
565
+ resolution = [50,50] : pair of integers
566
+ Resolution of the image.
567
+ box = None : in the format [[a,b], [c,d]]
568
+ If nontrivial, compute the landscape of this box. Default is the PyModule box.
569
+ plot = True : Boolean
570
+ If true, plots the images;
571
+ Returns
572
+ -------
573
+
574
+ The landscape of the module.
575
+
576
+ """
577
+ import matplotlib.pyplot as plt
578
+ if box is None:
579
+ box = self.get_box()
580
+ cdef Box[double] c_box = Box[double](box)
581
+ out = np.array(self.cmod.get_landscape(degree, k, c_box, resolution))
582
+ if plot:
583
+ aspect = (box[1][0]-box[0][0]) / (box[1][1]-box[0][1])
584
+ extent = [box[0][0], box[1][0], box[0][1], box[1][1]]
585
+ plt.imshow(out.T, origin="lower", extent=extent, aspect=aspect)
586
+ return out
587
+
588
+ def landscapes(self, degree:int, ks:list|np.ndarray=[0],box=None, resolution:list|np.ndarray=[100,100], bool plot=False):
589
+ r"""Computes the multiparameter landscape from a PyModule. Python interface only bifiltrations.
590
+
591
+ Parameters
592
+ ----------
593
+
594
+ - degree : integer
595
+ The homology degree of the landscape.
596
+ - ks = 0 : list of int
597
+ the k-th landscape
598
+ - resolution = [50,50] : pair of integers
599
+ Resolution of the image.
600
+ - box = None : in the format [[a,b], [c,d]]
601
+ If nontrivial, compute the landscape of this box. Default is the PyModule box.
602
+ - plot = True : bool
603
+ If true, plots the images;
604
+ Returns
605
+ -------
606
+
607
+ The landscapes of the module with parameters ks.
608
+
609
+ """
610
+ import matplotlib.pyplot as plt
611
+ if box is None:
612
+ box = self.get_box()
613
+ out = np.array(self.cmod.get_landscapes(degree, ks, Box[double](box), resolution))
614
+ if plot:
615
+ to_plot = np.sum(out, axis=0)
616
+ aspect = (box[1][0]-box[0][0]) / (box[1][1]-box[0][1])
617
+ extent = [box[0][0], box[1][0], box[0][1], box[1][1]]
618
+ plt.imshow(to_plot.T, origin="lower", extent=extent, aspect=aspect)
619
+ return out
620
+
621
+
622
+ def representation(self, degrees=None, double bandwidth=0.1,
623
+ resolution:Sequence[int]|int=50,
624
+ kernel:Literal["gaussian","linear","linear2","exponential"]|Callable = "gaussian",
625
+ bool signed=False,
626
+ bool normalize=False, bool plot=False,
627
+ bool save=False, int dpi=200,double p=2., box=None,
628
+ bool flatten=False, int n_jobs=0,
629
+ grid = None)->np.ndarray:
630
+ r"""Computes a representation of the module, using
631
+
632
+ [A Framework for Fast and Stable Representations of Multiparameter Persistent Homology Decompositions, Neurips2023]
633
+
634
+ Parameters
635
+ ----------
636
+
637
+ - degrees = None : integer list
638
+ If given returns only the image(s) of homology degrees `degrees`.
639
+ - bandwidth = 0.1 : float
640
+ Image parameter.
641
+ - resolution = [100,100] : pair of integers
642
+ Resolution of the image(s).
643
+ - normalize = True : Boolean
644
+ Ensures that the image belongs to [0,1].
645
+ - plot = False : Boolean
646
+ If true, plots the images;
647
+ - flatten=False :
648
+ If True, reshapes the output to a flattened shape.
649
+ - kernel: Either linear, gaussian, or callable
650
+ The kernel to apply to the matrix $(d(x,I), x \in \mathrm{pixels}, I\in \mathrm{summands})$.
651
+ signature should be : (distance matrix, summand_weights, bandwidth, p) -> representation
652
+
653
+ Returns
654
+ -------
655
+
656
+ The list of images, or the image of fixed dimension.
657
+ """
658
+ import matplotlib.pyplot as plt
659
+ # box = kwargs.get("box",[self.get_bottom(),self.get_top()])
660
+ if box is None:
661
+ box = self.get_box()
662
+ num_parameters = self.num_parameters
663
+ if degrees is None:
664
+ degrees = np.arange(self.max_degree +1)
665
+ num_degrees = len(degrees)
666
+ try:
667
+ int(resolution)
668
+ resolution = [resolution]*num_parameters
669
+ except:
670
+ pass
671
+
672
+ if grid is None:
673
+ grid = [np.linspace(*np.asarray(box)[:,parameter], num=res) for parameter, res in zip(range(num_parameters), resolution)]
674
+ else:
675
+ resolution = tuple(len(g) for g in grid)
676
+ coordinates = mpg.todense(grid)
677
+
678
+ if kernel == "linear":
679
+ assert not signed, "This kernel is not compatible with signed."
680
+ concatenated_images = self._compute_pixels(coordinates, degrees=degrees, box=box, delta=bandwidth, p=p, normalize=normalize,n_jobs=n_jobs)
681
+ else:
682
+ if kernel == "linear2":
683
+ def todo(PyModule_f64 mod_degree):
684
+ x = mod_degree.distance_to(coordinates,signed=signed)
685
+ w = mod_degree.get_interleavings()[None]**p
686
+ s = np.where(x>=0,1,-1) if signed else 1
687
+ x = np.abs(x)
688
+ return (s*np.where(x<bandwidth,(bandwidth-x)/bandwidth,0)*w).sum(1)
689
+ elif kernel == "gaussian":
690
+ def todo(PyModule_f64 mod_degree):
691
+ x = mod_degree.distance_to(coordinates,signed=signed)
692
+ w = mod_degree.get_interleavings()[None]**p
693
+ s = np.where(x>=0,1,-1) if signed else 1
694
+ return (s*np.exp( -.5*((x/bandwidth)**2))*w).sum(1)
695
+ elif kernel == "exponential":
696
+ def todo(PyModule_f64 mod_degree):
697
+ x = mod_degree.distance_to(coordinates,signed=signed)
698
+ w = mod_degree.get_interleavings()[None]**p
699
+ s = np.where(x>=0,1,-1) if signed else 1
700
+ x = np.abs(x)
701
+ return (s*np.exp( -((np.abs(x)/bandwidth)))*w).sum(1)
702
+ else:
703
+ assert callable(kernel), r"""
704
+ Kernel should be
705
+ gaussian, linear, linear2, exponential or callable,
706
+ with signature
707
+ (array[shape=(N, M)], array[shape=(M)])-> array(shape=(N)),
708
+ the first argument being a distance matrix (pts) vs (summands of the module)
709
+ and the second argument is a weight vector (weight(summand) for summand in module).
710
+ Note that the distance can be signed.
711
+ """
712
+ def todo(PyModule_f64 mod_degree):
713
+ x = mod_degree.distance_to(coordinates,signed=signed, n_jobs=n_jobs)
714
+ w = mod_degree.get_interleavings()[None]**p
715
+ return kernel(x/bandwidth,w)
716
+ concatenated_images = np.stack(
717
+ Parallel(n_jobs = n_jobs if n_jobs else -1, backend= "threading")(
718
+ delayed(todo)(self.get_module_of_degree(degree))
719
+ for degree in degrees
720
+ )
721
+ )
722
+
723
+ if flatten:
724
+ image_vector = concatenated_images.reshape((len(degrees),-1))
725
+ if plot:
726
+ raise ValueError("Unflatten to plot.")
727
+ return image_vector
728
+ else:
729
+ image_vector = concatenated_images.reshape((len(degrees),*resolution))
730
+ if plot:
731
+ assert num_parameters == 2, "Plot only available for 2-parameter modules"
732
+ import multipers.plots
733
+ i=0
734
+ n_plots = len(image_vector)
735
+ scale = 4
736
+ if n_plots >1:
737
+ fig, axs = plt.subplots(1,n_plots, figsize=(n_plots*scale,scale))
738
+ else:
739
+ fig = plt.gcf()
740
+ axs = [plt.gca()]
741
+ for image, degree, i in zip(image_vector, degrees, range(num_degrees)):
742
+ ax = axs[i]
743
+ temp = multipers.plots.plot_surface(grid, image.T, ax=ax)
744
+ plt.colorbar(temp, ax = ax)
745
+ if degree < 0 :
746
+ ax.set_title(rf"$H_{i}$ $2$-persistence image")
747
+ if degree >= 0:
748
+ ax.set_title(rf"$H_{degree}$ $2$-persistence image")
749
+ return image_vector
750
+
751
+ def euler_char(self, points:list|np.ndarray) -> np.ndarray:
752
+ r""" Computes the Euler Characteristic of the filtered complex at given (multiparameter) time
753
+
754
+ Parameters
755
+ ----------
756
+
757
+ points: list[float] | list[list[float]] | np.ndarray
758
+ List of filtration values on which to compute the euler characteristic.
759
+ WARNING FIXME : the points have to have the same dimension as the simplextree.
760
+
761
+ Returns
762
+ -------
763
+
764
+ The list of euler characteristic values
765
+ """
766
+ if len(points) == 0:
767
+ return []
768
+ if type(points[0]) is float:
769
+ points = [points]
770
+ if type(points) is np.ndarray:
771
+ assert len(points.shape) in [1,2]
772
+ if len(points.shape) == 1:
773
+ points = [points]
774
+
775
+ cdef double[:,:] points_view = np.asarray(points, dtype = np.float64)
776
+ cdef vector[One_critical_filtration[double]] c_points = _py2v1c_f64(points_view)
777
+ # cdef One_critical_filtration temp
778
+ # for point in points:
779
+ # temp.clear()
780
+ # for truc in point:
781
+ # temp.push_back(<double>(truc))
782
+ # c_points.push_back(temp)
783
+ cdef Module[double] c_mod = self.cmod
784
+ with nogil:
785
+ c_euler = c_mod.euler_curve(c_points)
786
+ euler = c_euler
787
+ return np.asarray(euler, dtype=int)
788
+ def to_idx(self,grid):
789
+ cdef vector[vector[double]] cgrid = grid
790
+ cdef vector[vector[pair[vector[vector[int]],vector[vector[int]]]]] out
791
+ with nogil:
792
+ out = self.cmod.to_idx(cgrid)
793
+ return tuple(tuple((np.asarray(I.first,dtype=np.int64), np.asarray(I.second, dtype=np.int64)) for I in Is_of_degree) for Is_of_degree in out)
794
+
795
+ @cython.wraparound(False)
796
+ @cython.boundscheck(False)
797
+ def to_flat_idx(self,grid):
798
+ if len(self) == 0:
799
+ return np.empty((2,0), dtype = np.int32), np.empty((0, self.num_parameters), dtype = np.int32), np.empty((0, self.num_parameters), dtype = np.int32)
800
+ cdef vector[vector[double]] cgrid = grid
801
+ cdef vector[vector[vector[int]]] out
802
+ cdef int num_summands, num_births, num_deaths
803
+ cdef int num_parameters = self.num_parameters
804
+ with nogil:
805
+ out = self.cmod.to_flat_idx(cgrid)
806
+ num_summands = out[0][0].size()
807
+ num_births = out[1].size()
808
+ num_deaths = out[2].size()
809
+ idx = np.empty((2, num_summands),dtype=np.int32 )
810
+ births = np.empty((num_births,num_parameters),dtype=np.int32)
811
+ deaths = np.empty((num_deaths,num_parameters),dtype=np.int32)
812
+
813
+ cdef int32_t[:,:] idx_view = idx
814
+ cdef int32_t[:,:] births_view = births
815
+ cdef int32_t[:,:] deaths_view = deaths
816
+
817
+ with nogil:
818
+ for i in range(num_summands):
819
+ idx_view[0,i] = out[0][0][i]
820
+ idx_view[1,i] = out[0][1][i]
821
+ for i in range(num_births):
822
+ for j in range(num_parameters):
823
+ births_view[i,j] = out[1][i][j]
824
+ for i in range(num_deaths):
825
+ for j in range(num_parameters):
826
+ deaths_view[i,j] = out[2][i][j]
827
+
828
+ return idx, births,deaths
829
+
830
+ def distances_idx_to(self, pts, bool full=False, int n_jobs=1):
831
+ pts = np.asarray(pts)
832
+ if pts.ndim == 1:
833
+ pts = pts[None]
834
+ cdef vector[vector[double]] cpts = pts
835
+ cdef vector[vector[vector[int]]] out
836
+ with nogil:
837
+ out = self.cmod.compute_distances_idx_to(cpts,full, n_jobs)
838
+ return np.asarray(out, dtype=np.int32)
839
+
840
+ def distance_to(self, pts, bool signed=False, int n_jobs = 0)->np.ndarray:
841
+ r"""
842
+ Distance from a point to each summand's support.
843
+ Signed distance is the distance to the boundary,
844
+ with negative values inside the summands.
845
+
846
+ pts of shape (num_pts, num_parameters)
847
+
848
+ output shape : (num_pts,num_summands)
849
+ """
850
+ pts = np.asarray(pts)
851
+ if pts.ndim == 1:
852
+ pts = pts[None]
853
+ assert pts.shape[-1] == self.num_parameters
854
+ cdef vector[vector[double]] cpts = pts
855
+ # cdef vector[vector[double]] out
856
+ to_fill = np.empty(shape=(cpts.size(),len(self)), dtype = np.float64)
857
+ cdef double[:,:] c_to_fill = to_fill
858
+ cdef double* data_ptr = &c_to_fill[0,0]
859
+ with nogil:
860
+ self.cmod.compute_distances_to(data_ptr, cpts,signed, n_jobs)
861
+ return to_fill
862
+
863
+ def get_interleavings(self,box=None):
864
+ if box is None:
865
+ box = self.get_box()
866
+ cdef Box[double] cbox = Box[double](box)
867
+ return np.asarray(self.cmod.get_interleavings(cbox))
868
+
869
+ cdef class PyMultiDiagramPoint_f64:
870
+ cdef MultiDiagram_point[One_critical_filtration[double]] point
871
+ cdef set(self, MultiDiagram_point[One_critical_filtration[double]] pt):
872
+ self.point = pt
873
+ return self
874
+
875
+ def get_degree(self):
876
+ return self.point.get_dimension()
877
+ def get_birth(self):
878
+ cdef One_critical_filtration[double] v = self.point.get_birth()
879
+ return _ff21cview_f64(&v, copy=True)
880
+ def get_death(self):
881
+ cdef One_critical_filtration[double] v = self.point.get_death()
882
+ return _ff21cview_f64(&v, copy=True)
883
+
884
+
885
+ cdef class PyMultiDiagram_f64:
886
+ r"""
887
+ Stores the diagram of a PyModule on a line
888
+ """
889
+ cdef MultiDiagram[One_critical_filtration[double], double] multiDiagram
890
+ cdef set(self, MultiDiagram[One_critical_filtration[double], double] m):
891
+ self.multiDiagram = m
892
+ return self
893
+ def get_points(self, degree:int=-1) -> np.ndarray:
894
+ cdef vector[pair[vector[double],vector[double]]] out = self.multiDiagram.get_points(degree)
895
+ if len(out) == 0 and len(self) == 0:
896
+ return np.empty() # TODO Retrieve good number of parameters if there is no points in diagram
897
+ if len(out) == 0:
898
+ return np.empty((0,2,self.multiDiagram.at(0).get_dimension())) # gets the number of parameters
899
+ return np.array(out)
900
+ def to_multipers(self, dimension:int):
901
+ return self.multiDiagram.to_multipers(dimension)
902
+ def __len__(self) -> int:
903
+ return self.multiDiagram.size()
904
+ def __getitem__(self,i:int) -> PyMultiDiagramPoint_f64:
905
+ return PyMultiDiagramPoint_f64().set(self.multiDiagram.at(i % self.multiDiagram.size()))
906
+ cdef class PyMultiDiagrams_f64:
907
+ """
908
+ Stores the barcodes of a PyModule on multiple lines
909
+ """
910
+ cdef MultiDiagrams[One_critical_filtration[double], double] multiDiagrams
911
+ cdef set(self,MultiDiagrams[One_critical_filtration[double], double] m):
912
+ self.multiDiagrams = m
913
+ return self
914
+ def to_multipers(self):
915
+ out = self.multiDiagrams.to_multipers()
916
+ return [np.asarray(summand) for summand in out]
917
+ def __getitem__(self,i:int):
918
+ if i >=0 :
919
+ return PyMultiDiagram_f64().set(self.multiDiagrams.at(i))
920
+ else:
921
+ return PyMultiDiagram_f64().set(self.multiDiagrams.at( self.multiDiagrams.size() - i))
922
+ def __len__(self):
923
+ return self.multiDiagrams.size()
924
+ def get_points(self, degree:int=-1):
925
+ return self.multiDiagrams.get_points()
926
+ cdef _get_plot_bars(self, dimension:int=-1, min_persistence:float=0):
927
+ return self.multiDiagrams._for_python_plot(dimension, min_persistence);
928
+ def plot(self, degree:int=-1, min_persistence:float=0):
929
+ """
930
+ Plots the barcodes.
931
+
932
+ Parameters
933
+ ----------
934
+
935
+ - degree:int=-1
936
+ Only plots the bars of specified homology degree. Useful when the multidiagrams contains multiple dimenions
937
+ - min_persistence:float=0
938
+ Only plot bars of length greater than this value. Useful to reduce the time to plot.
939
+
940
+ Warning
941
+ -------
942
+
943
+ If the barcodes are not thresholded, essential barcodes will not be displayed !
944
+
945
+ """
946
+ from cycler import cycler
947
+ import matplotlib
948
+ import matplotlib.pyplot as plt
949
+ if len(self) == 0: return
950
+ _cmap = matplotlib.colormaps["Spectral"]
951
+ multibarcodes_, colors = self._get_plot_bars(degree, min_persistence)
952
+ n_summands = np.max(colors)+1 if len(colors)>0 else 1
953
+
954
+ plt.rc('axes', prop_cycle = cycler('color', [_cmap(i/n_summands) for i in colors]))
955
+ return plt.plot(*multibarcodes_)
956
+
957
+
958
+ cdef dump_summand_f64(Summand[double]& summand):
959
+ cdef vector[One_critical_filtration[double]] births = summand.get_birth_list()
960
+ cdef vector[One_critical_filtration[double]] deaths = summand.get_death_list()
961
+ return (
962
+ _vff21cview_f64(births, copy=True), ## copy as local variables
963
+ _vff21cview_f64(deaths, copy=True),
964
+ summand.get_dimension(),
965
+ )
966
+
967
+ cdef inline Summand[double] summand_from_dump_f64(summand_dump):
968
+ cdef vector[One_critical_filtration[double]] births = _py2v1c_f64(summand_dump[0])
969
+ cdef vector[One_critical_filtration[double]] deaths = _py2v1c_f64(summand_dump[1])
970
+ cdef int dim = summand_dump[2]
971
+ return Summand[double](births,deaths,dim)
972
+
973
+ cdef dump_cmod_f64(Module[double]& mod):
974
+ cdef Box[double] cbox = mod.get_box()
975
+ cdef int dim = mod.get_dimension()
976
+ cdef cnp.ndarray[double, ndim=1] bottom_corner = _ff21cview_f64(&cbox.get_lower_corner())
977
+ cdef cnp.ndarray[double, ndim=1] top_corner = _ff21cview_f64(&cbox.get_upper_corner())
978
+ box = np.asarray([bottom_corner, top_corner])
979
+ summands = tuple(dump_summand_f64(summand) for summand in mod)
980
+ return box, summands
981
+
982
+ cdef Module[double] cmod_from_dump_f64(module_dump):
983
+ box = module_dump[0]
984
+ summands = module_dump[1]
985
+ cdef Module[double] out_module = Module[double]()
986
+ out_module.set_box(Box[double](box))
987
+ for i in range(len(summands)):
988
+ out_module.add_summand(summand_from_dump_f64(summands[i]))
989
+ return out_module
990
+
991
+
992
+ def from_dump_f64(dump)->PyModule_f64:
993
+ r"""Retrieves a PyModule from a previous dump.
994
+
995
+ Parameters
996
+ ----------
997
+
998
+ dump: either the output of the dump function, or a file containing the output of a dump.
999
+ The dumped module to retrieve
1000
+
1001
+ Returns
1002
+ -------
1003
+
1004
+ PyModule
1005
+ The retrieved module.
1006
+ """
1007
+ # TODO : optimize...
1008
+ mod = PyModule_f64()
1009
+ if type(dump) is str:
1010
+ dump = pickle.load(open(dump, "rb"))
1011
+ cdef Module[double] cmod = cmod_from_dump_f64(dump)
1012
+ mod.cmod = cmod
1013
+ return mod
1014
+
1015
+ cdef class PySummand_f32:
1016
+ r"""
1017
+ Stores a Summand of a PyModule
1018
+ """
1019
+ cdef Summand[float] sum
1020
+
1021
+ def get_birth_list(self):
1022
+ cdef vector[One_critical_filtration[float]] v = self.sum.get_birth_list()
1023
+ return _vff21cview_f32(v, copy = True, duplicate = self.num_parameters())
1024
+
1025
+ def get_death_list(self):
1026
+ cdef vector[One_critical_filtration[float]] v = self.sum.get_death_list()
1027
+ return _vff21cview_f32(v, copy = True, duplicate = self.num_parameters())
1028
+ @property
1029
+ def degree(self)->int:
1030
+ return self.sum.get_dimension()
1031
+
1032
+ cdef set(self, Summand[float]& summand):
1033
+ self.sum = summand
1034
+ return self
1035
+ def get_bounds(self):
1036
+ cdef pair[One_critical_filtration[float],One_critical_filtration[float]] cbounds
1037
+ with nogil:
1038
+ cbounds = self.sum.get_bounds().get_bounding_corners()
1039
+ return _ff21cview_f32(&cbounds.first).copy(), _ff21cview_f32(&cbounds.second).copy()
1040
+ @property
1041
+ def dtype(self):
1042
+ return np.float32
1043
+
1044
+ def num_parameters(self):
1045
+ cdef vector[One_critical_filtration[float]] v = self.sum.get_birth_list()
1046
+ if v[0].is_finite():
1047
+ return v[0].num_parameters()
1048
+ v = self.sum.get_death_list()
1049
+ return v[0].num_parameters()
1050
+
1051
+ cdef inline get_summand_filtration_values_f32(Summand[float] summand):
1052
+ r"""
1053
+ Returns a list (over parameter) of the filtrations values of this parameter.
1054
+ """
1055
+ cdef vector[One_critical_filtration[float]] vb = summand.get_birth_list()
1056
+ cdef vector[One_critical_filtration[float]] vd = summand.get_death_list()
1057
+
1058
+ if vb[0].is_finite():
1059
+ if vd[0].is_finite():
1060
+ pts = np.concatenate([_vff21cview_f32(vb, copy=True),
1061
+ _vff21cview_f32(vd, copy=True)],axis=0)
1062
+ else:
1063
+ pts = np.array(_vff21cview_f32(vb, copy=True))
1064
+ else:
1065
+ if vd[0].is_finite():
1066
+ pts = np.array(_vff21cview_f32(vd, copy=True))
1067
+ else:
1068
+ return []
1069
+
1070
+ num_parameters = pts.shape[1]
1071
+ out = [np.unique(pts[:,parameter]) for parameter in range(num_parameters)]
1072
+ out = [f[:-1] if f[-1] == np.inf else f for f in out]
1073
+ out = [f[1:] if f[0] == -np.inf else f for f in out]
1074
+ return out
1075
+
1076
+ cdef class PyBox_f32:
1077
+ cdef Box[float] box
1078
+ def __cinit__(self, vector[float]& bottomCorner, vector[float]& topCorner):
1079
+ self.box = Box[float](bottomCorner, topCorner)
1080
+ @property
1081
+ def num_parameters(self):
1082
+ cdef size_t dim = self.box.get_lower_corner().num_parameters()
1083
+ if dim == self.box.get_upper_corner().num_parameters(): return dim
1084
+ else: print("Bad box definition.")
1085
+ def contains(self, x):
1086
+ return self.box.contains(x)
1087
+ cdef set(self, Box[float]& b):
1088
+ self.box = b
1089
+ return self
1090
+
1091
+ def get(self):
1092
+ return [<vector[float]>self.box.get_lower_corner(), <vector[float]>self.box.get_upper_corner()]
1093
+ def to_multipers(self):
1094
+ #assert (self.get_dimension() == 2) "Multipers only works in dimension 2 !"
1095
+ return np.array(self.get()).flatten(order = 'F')
1096
+ @property
1097
+ def dtype(self):
1098
+ return np.float32
1099
+
1100
+
1101
+
1102
+ cdef class PyModule_f32:
1103
+ r"""
1104
+ Stores a representation of a n-persistence module.
1105
+ """
1106
+ cdef Module[float] cmod
1107
+
1108
+ @property
1109
+ def dtype(self):
1110
+ return np.float32
1111
+
1112
+ cdef set(self, Module[float] m):
1113
+ self.cmod = m
1114
+ def merge(self, PyModule_f32 other, int dim=-1):
1115
+ r"""
1116
+ Merges two modules into one
1117
+ """
1118
+ cdef Module[float] c_other = other.cmod
1119
+ with nogil:
1120
+ for summand in c_other:
1121
+ self.cmod.add_summand(summand, dim)
1122
+ return self
1123
+
1124
+ def _set_from_ptr(self, intptr_t module_ptr):
1125
+ r"""
1126
+ Copy module from a memory pointer. Unsafe.
1127
+ """
1128
+ self.cmod = move(dereference(<Module[float]*>(module_ptr)))
1129
+ def set_box(self, PyBox_f32 pybox):
1130
+ cdef Box[float] cbox = pybox.box
1131
+ with nogil:
1132
+ self.cmod.set_box(cbox)
1133
+ return self
1134
+ def get_module_of_degree(self, int degree)->PyModule_f32: # TODO : in c++ ?
1135
+ r"""
1136
+ Returns a copy of a module of fixed degree.
1137
+ """
1138
+ pmodule = PyModule_f32()
1139
+ cdef Box[float] c_box = self.cmod.get_box()
1140
+ pmodule.cmod.set_box(c_box)
1141
+ with nogil:
1142
+ for summand in self.cmod:
1143
+ if summand.get_dimension() == degree:
1144
+ pmodule.cmod.add_summand(summand)
1145
+ return pmodule
1146
+ def get_module_of_degrees(self, degrees:Iterable[int])->PyModule_f32: # TODO : in c++ ?
1147
+ r"""
1148
+ Returns a copy of the summands of degrees in `degrees`
1149
+ """
1150
+ pmodule = PyModule_f32()
1151
+ cdef Box[float] c_box = self.cmod.get_box()
1152
+ pmodule.cmod.set_box(c_box)
1153
+ cdef vector[int] cdegrees = degrees
1154
+ with nogil:
1155
+ for summand in self.cmod:
1156
+ for d in cdegrees:
1157
+ if d == summand.get_dimension():
1158
+ pmodule.cmod.add_summand(summand)
1159
+ return pmodule
1160
+ def __len__(self)->int:
1161
+ return self.cmod.size()
1162
+ def get_bottom(self)->np.ndarray:
1163
+ r"""
1164
+ Bottom of the box of the module
1165
+ """
1166
+ return np.asarray(<vector[float]>(self.cmod.get_box().get_lower_corner()))
1167
+ def get_top(self)->np.ndarray:
1168
+ r"""
1169
+ Top of the box of the module
1170
+ """
1171
+ return np.asarray(<vector[float]>(self.cmod.get_box().get_upper_corner()))
1172
+ def get_box(self)->np.ndarray:
1173
+ r"""
1174
+ Returns the current bounding box of the module.
1175
+ """
1176
+ return np.asarray([self.get_bottom(), self.get_top()])
1177
+ @property
1178
+ def max_degree(self)->int:
1179
+ r"""
1180
+ Returns the maximum degree of the module.
1181
+ """
1182
+ return self.cmod.get_dimension()
1183
+ @property
1184
+ def num_parameters(self)->int:
1185
+ cdef size_t dim = self.cmod.get_box().get_lower_corner().num_parameters()
1186
+ assert dim == self.cmod.get_box().get_upper_corner().num_parameters(), "Bad box definition, cannot infer num_parameters."
1187
+ return dim
1188
+ def dump(self, path:str|None=None):
1189
+ r"""
1190
+ Dumps the module into a pickle-able format.
1191
+
1192
+ Parameters
1193
+ ----------
1194
+
1195
+ path:str=None (optional) saves the pickled module in specified path
1196
+
1197
+ Returns
1198
+ -------
1199
+
1200
+ list of list, encoding the module, which can be retrieved with the function `from_dump`.
1201
+ """
1202
+ ## TODO : optimize, but not really used.
1203
+ return dump_cmod_f32(self.cmod)
1204
+ def __getstate__(self):
1205
+ return self.dump()
1206
+ def __setstate__(self,dump):
1207
+ cdef Module[float] cmod = cmod_from_dump_f32(dump)
1208
+ self.cmod = cmod
1209
+ return
1210
+ def __getitem__(self, int i) -> PySummand_f32:
1211
+ if i == slice(None):
1212
+ return self
1213
+ summand = PySummand_f32()
1214
+ summand.set(self.cmod.at(i % self.cmod.size()))
1215
+ return summand
1216
+ def __iter__(self):
1217
+ cdef int num_summands = self.cmod.size()
1218
+ for i in range(num_summands):
1219
+ summand = PySummand_f32()
1220
+ summand.set(self.cmod.at(i)) ## hmm copy. maybe do summand from ptr
1221
+ yield summand
1222
+
1223
+ def get_bounds(self):
1224
+ r"""
1225
+ Computes bounds from the summands' bounds.
1226
+ Useful to change this' box.
1227
+ """
1228
+ cdef pair[One_critical_filtration[float],One_critical_filtration[float]] cbounds
1229
+ with nogil:
1230
+ cbounds = self.cmod.get_bounds().get_bounding_corners()
1231
+ return _ff21cview_f32(&cbounds.first).copy(), _ff21cview_f32(&cbounds.second).copy()
1232
+ def rescale(self,rescale_factors, int degree=-1):
1233
+ r"""
1234
+ Rescales the fitlration values of the summands by this rescaling vector.
1235
+ """
1236
+ cdef vector[float] crescale_factors = rescale_factors
1237
+ with nogil:
1238
+ self.cmod.rescale(crescale_factors,degree)
1239
+ def translate(self,translation, int degree=-1):
1240
+ r"""
1241
+ Translates the module in the filtration space by this vector.
1242
+ """
1243
+ cdef vector[float] ctranslation = translation
1244
+ with nogil:
1245
+ self.cmod.translate(ctranslation,degree)
1246
+
1247
+ def get_filtration_values(self, bool unique=True):
1248
+ r"""
1249
+ Retrieves all filtration values of the summands of the module.
1250
+
1251
+ Output format
1252
+ -------------
1253
+
1254
+ list of filtration values for parameter.
1255
+ """
1256
+ if len(self) ==0:
1257
+ return np.empty((self.num_parameters,0))
1258
+ values = tuple(tuple(stuff) if len(stuff:=get_summand_filtration_values_f32(summand)) == self.num_parameters else list(stuff) + [[]]*(self.num_parameters - len(stuff)) for summand in self.cmod)
1259
+ try:
1260
+ values = tuple(np.concatenate([
1261
+ f[parameter]
1262
+ for f in values
1263
+ ], axis=0) for parameter in range(self.num_parameters)
1264
+ )
1265
+ except:
1266
+ return values
1267
+ if unique:
1268
+ return [np.unique(f) for f in values]
1269
+ return values
1270
+
1271
+ def plot(self, int degree=-1,**kwargs)->None:
1272
+ r"""Shows the module on a plot. Each color corresponds to an apprimation summand of the module, and its shape corresponds to its support.
1273
+ Only works with 2-parameter modules.
1274
+
1275
+ Parameters
1276
+ ----------
1277
+ degree = -1 : integer
1278
+ If positive returns only the image of dimension `dimension`.
1279
+ box=None : of the form [[b_x,b_y], [d_x,d_y]] where b,d are the bottom and top corner of the rectangle.
1280
+ If non-None, will plot the module on this specific rectangle.
1281
+ min_persistence =0 : float
1282
+ Only plots the summand with a persistence above this threshold.
1283
+ separated=False : bool
1284
+ If true, plot each summand in a different plot.
1285
+ alpha=1 : float
1286
+ Transparancy parameter
1287
+ save = False : string
1288
+ if nontrivial, will save the figure at this path
1289
+
1290
+
1291
+ Returns
1292
+ -------
1293
+ The figure of the plot.
1294
+ """
1295
+ from multipers.plots import plot2d_PyModule
1296
+ import matplotlib.pyplot as plt
1297
+ box = kwargs.pop('box', self.get_box())
1298
+ if (len(box[0]) != 2):
1299
+ print("Filtration size :", len(box[0]), " != 2")
1300
+ return
1301
+ if(degree < 0):
1302
+ dims = np.unique(self.get_dimensions())
1303
+ separated = kwargs.pop("separated", False)
1304
+ ndim = len(dims)
1305
+ scale = kwargs.pop("scale", 4)
1306
+ if separated:
1307
+ fig = None
1308
+ axes = None
1309
+ elif ndim > 1:
1310
+ fig, axes = plt.subplots(1,ndim, figsize=(ndim*scale,scale))
1311
+ else:
1312
+ fig = plt.gcf()
1313
+ axes = [plt.gca()]
1314
+ for dim_idx in range(ndim):
1315
+ if not separated:
1316
+ plt.sca(axes[dim_idx])
1317
+ self.plot(dims[dim_idx],box=box, separated = separated, **kwargs)
1318
+ return
1319
+ corners = self.cmod.get_corners_of_dimension(degree)
1320
+ plot2d_PyModule(corners, box=box, dimension=degree, **kwargs)
1321
+ return
1322
+ def degree_splits(self):
1323
+ return np.asarray(self.cmod.get_degree_splits(), dtype=np.int64)
1324
+ def _compute_pixels(self,coordinates:np.ndarray,
1325
+ degrees=None, box=None, float delta=.1,
1326
+ float p=1., bool normalize=False, int n_jobs=0):
1327
+ r"""
1328
+ Computes the image of the module at the given coordinates
1329
+ """
1330
+ if degrees is not None: assert np.all(degrees[:-1] <= degrees[1:]), "Degrees have to be sorted"
1331
+ cdef vector[int] cdegrees = np.arange(self.max_degree +1) if degrees is None else degrees
1332
+ pybox = PyBox_f32(*self.get_box()) if box is None else PyBox_f32(*box)
1333
+ cdef Box[float] cbox = pybox.box
1334
+ cdef vector[vector[float]] ccoords = coordinates
1335
+ cdef vector[vector[float]] out
1336
+ with nogil:
1337
+ out = self.cmod.compute_pixels(ccoords, cdegrees, cbox, delta, p, normalize, n_jobs)
1338
+ return np.asarray(out)
1339
+ def barcode(self, basepoint, int degree = -1,*, bool threshold = False): # TODO direction vector interface
1340
+ r"""Computes the barcode of module along a lines.
1341
+
1342
+ Parameters
1343
+ ----------
1344
+
1345
+ basepoint : vector
1346
+ basepoint of the lines on which to compute the barcodes, i.e. a point on the line
1347
+ degree = -1 : integer
1348
+ Homology degree on which to compute the bars. If negative, every dimension is computed
1349
+ box (default) :
1350
+ box on which to compute the barcodes if basepoints is not specified. Default is a linspace of lines crossing that box.
1351
+ threshold = False :
1352
+ Thre
1353
+
1354
+ Warning
1355
+ -------
1356
+
1357
+ If the barcodes are not thresholded, essential barcodes will not be plot-able.
1358
+
1359
+ Returns
1360
+ -------
1361
+
1362
+ PyMultiDiagrams
1363
+ Structure that holds the barcodes. Barcodes can be retrieved with a .get_points() or a .to_multipers() or a .plot().
1364
+ """
1365
+ out = PyMultiDiagram_f32()
1366
+ out.set(self.cmod.get_barcode(Line[float](_py21c_f32(np.asarray(basepoint, dtype=np.float32))), degree, threshold))
1367
+ return out
1368
+ @staticmethod
1369
+ cdef _threshold_bc(bc):
1370
+ return tuple(np.fromiter((a for a in stuff if a[0] < np.inf), dtype=np.dtype((np.float32,2)) ) for stuff in bc)
1371
+ @staticmethod
1372
+ def _bc_to_full(bcs, basepoint, direction=None):
1373
+ # i, (b sv d), coords
1374
+ basepoint = np.asarray(basepoint)[None,None,:]
1375
+ direction = 1 if direction is None else np.asarray(direction)[None,None,:]
1376
+ return tuple(bc[:,:,None]*direction + basepoint for bc in bcs)
1377
+ def barcode2(self, basepoint, direction=None, int degree = -1,*, bool threshold = False, bool keep_inf = True, bool full = False): # TODO direction vector interface
1378
+ r"""
1379
+ Compute the 1d-barcode a diagonal line based on basepoint, with some direction.
1380
+
1381
+ Parameters
1382
+ ----------
1383
+
1384
+ - basepoint: 1d array
1385
+ - directiont: 1d array or None, if None: diagonal
1386
+ - degree: int the degree to compute (-1 means all)
1387
+ - threshold: bool if True, threshold the barcode to the modules box
1388
+ - keep_inf: bool if False, removes trivial bars
1389
+ Note that this removes the order w.r.t. the summands in that case
1390
+ - full:bool if True, returns the coordinates of the barcode instead of the coordinate in the line.
1391
+
1392
+ The output is of the form
1393
+
1394
+ tuple[np.ndarray of shape (num_bars,2)] or tuple[array of shape (num_bar, 2, num_parameters)]
1395
+ """
1396
+ basepoint = np.asarray(basepoint, dtype=np.float32)
1397
+ if direction is None:
1398
+ bc = tuple(np.asarray(x).reshape(-1,2) for x in self.cmod.get_barcode2(Line[float](_py21c_f32(basepoint)), degree))
1399
+ else:
1400
+ direction = np.asarray(direction, dtype = np.float32)
1401
+ bc = tuple(np.asarray(x).reshape(-1,2) for x in self.cmod.get_barcode2(Line[float](_py21c_f32(basepoint), _py21c_f32(direction)), degree))
1402
+ if not keep_inf:
1403
+ bc = PyModule_f32._threshold_bc(bc)
1404
+ if full:
1405
+ bc = PyModule_f32._bc_to_full(bc, basepoint, direction)
1406
+
1407
+ return bc
1408
+
1409
+ def get_dimensions(self):
1410
+ cdef int num_summands = len(self)
1411
+ out = np.empty(shape=num_summands, dtype=np.int32)
1412
+ cdef int32_t[:] c_out = out
1413
+ for i in range(num_summands):
1414
+ c_out[i] = self.cmod.at(i).get_dimension()
1415
+ return out
1416
+
1417
+ def barcodes(self, int degree, basepoints = None, num=100, box = None,threshold = False):
1418
+ r"""Computes barcodes of module along a set of lines.
1419
+
1420
+ Parameters
1421
+ ----------
1422
+
1423
+ basepoints = None : list of vectors
1424
+ basepoints of the lines on which to compute the barcodes.
1425
+ degree = -1 : integer
1426
+ Homology degree on which to compute the bars. If negative, every dimension is computed
1427
+ box (default) :
1428
+ box on which to compute the barcodes if basepoints is not specified. Default is a linspace of lines crossing that box.
1429
+ num:int=100
1430
+ if basepoints is not specified, defines the number of lines to consider.
1431
+ threshold = False : threshold t
1432
+ Resolution of the image(s).
1433
+
1434
+ Warning
1435
+ -------
1436
+
1437
+ If the barcodes are not thresholded, essential barcodes will not be plot-able.
1438
+
1439
+ Returns
1440
+ -------
1441
+
1442
+ PyMultiDiagrams
1443
+ Structure that holds the barcodes. Barcodes can be retrieved with a .get_points() or a .to_multipers() or a .plot().
1444
+ """
1445
+ out = PyMultiDiagrams_f32()
1446
+ if box is None:
1447
+ box = [self.get_bottom(), self.get_top()]
1448
+ if (len(box[0]) != 2) and (basepoints is None):
1449
+ raise ValueError("Basepoints has to be specified for filtration dimension >= 3 !")
1450
+ elif basepoints is None:
1451
+ h = box[1][1] - box[0][1]
1452
+ basepoints = np.linspace([box[0][0] - h,box[0][1]], [box[1][0],box[0][1]], num=num)
1453
+ else :
1454
+ num=len(basepoints)
1455
+
1456
+ cdef float[:,:] basepoints_view = np.asarray(basepoints, dtype = np.float32)
1457
+ cdef vector[One_critical_filtration[float]] cbasepoints = _py2v1c_f32(basepoints_view)
1458
+
1459
+ out.set(self.cmod.get_barcodes(cbasepoints, degree, threshold))
1460
+ return out
1461
+
1462
+ def barcodes2(self, int degree = -1, basepoints = None, int num=100, box = None, bool threshold = False):
1463
+ r"""Computes barcodes of module along a set of lines.
1464
+
1465
+ Parameters
1466
+ ----------
1467
+
1468
+ basepoints = None : list of vectors
1469
+ basepoints of the lines on which to compute the barcodes.
1470
+ degree = -1 : integer
1471
+ Homology degree on which to compute the bars. If negative, every dimension is computed
1472
+ box (default) :
1473
+ box on which to compute the barcodes if basepoints is not specified. Default is a linspace of lines crossing that box.
1474
+ num:int=100
1475
+ if basepoints is not specified, defines the number of lines to consider.
1476
+ threshold = False : threshold t
1477
+ Resolution of the image(s).
1478
+
1479
+ Warning
1480
+ -------
1481
+
1482
+ If the barcodes are not thresholded, essential barcodes will not be plot-able.
1483
+
1484
+ Returns
1485
+ -------
1486
+
1487
+ tuple of 1d barcodes, based on basepoint, with direction (1,1)
1488
+ """
1489
+ if box is None:
1490
+ box = [self.get_bottom(), self.get_top()]
1491
+ if (len(box[0]) != 2) and (basepoints is None):
1492
+ raise ValueError("Basepoints has to be specified for filtration dimension >= 3 !")
1493
+ elif basepoints is None:
1494
+ h = box[1][1] - box[0][1]
1495
+ basepoints = np.linspace([box[0][0] - h,box[0][1]], [box[1][0],box[0][1]], num=num)
1496
+ else :
1497
+ num=len(basepoints)
1498
+
1499
+ basepoints = np.asarray(basepoints, dtype=np.float32)
1500
+ cdef vector[Line[float]] cbasepoints
1501
+ for i in range(num):
1502
+ cbasepoints.push_back(Line[float](_py21c_f32(basepoints[i])))
1503
+ return tuple(np.asarray(bc) for bc in self.cmod.get_barcodes2(cbasepoints, degree))
1504
+
1505
+ def landscape(self, degree:int, k:int=0,box:Sequence|np.ndarray|None=None, resolution:Sequence=[100,100], bool plot=False):
1506
+ r"""Computes the multiparameter landscape from a PyModule. Python interface only bifiltrations.
1507
+
1508
+ Parameters
1509
+ ----------
1510
+
1511
+ degree : integer
1512
+ The homology degree of the landscape.
1513
+ k = 0 : int
1514
+ the k-th landscape
1515
+ resolution = [50,50] : pair of integers
1516
+ Resolution of the image.
1517
+ box = None : in the format [[a,b], [c,d]]
1518
+ If nontrivial, compute the landscape of this box. Default is the PyModule box.
1519
+ plot = True : Boolean
1520
+ If true, plots the images;
1521
+ Returns
1522
+ -------
1523
+
1524
+ The landscape of the module.
1525
+
1526
+ """
1527
+ import matplotlib.pyplot as plt
1528
+ if box is None:
1529
+ box = self.get_box()
1530
+ cdef Box[float] c_box = Box[float](box)
1531
+ out = np.array(self.cmod.get_landscape(degree, k, c_box, resolution))
1532
+ if plot:
1533
+ aspect = (box[1][0]-box[0][0]) / (box[1][1]-box[0][1])
1534
+ extent = [box[0][0], box[1][0], box[0][1], box[1][1]]
1535
+ plt.imshow(out.T, origin="lower", extent=extent, aspect=aspect)
1536
+ return out
1537
+
1538
+ def landscapes(self, degree:int, ks:list|np.ndarray=[0],box=None, resolution:list|np.ndarray=[100,100], bool plot=False):
1539
+ r"""Computes the multiparameter landscape from a PyModule. Python interface only bifiltrations.
1540
+
1541
+ Parameters
1542
+ ----------
1543
+
1544
+ - degree : integer
1545
+ The homology degree of the landscape.
1546
+ - ks = 0 : list of int
1547
+ the k-th landscape
1548
+ - resolution = [50,50] : pair of integers
1549
+ Resolution of the image.
1550
+ - box = None : in the format [[a,b], [c,d]]
1551
+ If nontrivial, compute the landscape of this box. Default is the PyModule box.
1552
+ - plot = True : bool
1553
+ If true, plots the images;
1554
+ Returns
1555
+ -------
1556
+
1557
+ The landscapes of the module with parameters ks.
1558
+
1559
+ """
1560
+ import matplotlib.pyplot as plt
1561
+ if box is None:
1562
+ box = self.get_box()
1563
+ out = np.array(self.cmod.get_landscapes(degree, ks, Box[float](box), resolution))
1564
+ if plot:
1565
+ to_plot = np.sum(out, axis=0)
1566
+ aspect = (box[1][0]-box[0][0]) / (box[1][1]-box[0][1])
1567
+ extent = [box[0][0], box[1][0], box[0][1], box[1][1]]
1568
+ plt.imshow(to_plot.T, origin="lower", extent=extent, aspect=aspect)
1569
+ return out
1570
+
1571
+
1572
+ def representation(self, degrees=None, double bandwidth=0.1,
1573
+ resolution:Sequence[int]|int=50,
1574
+ kernel:Literal["gaussian","linear","linear2","exponential"]|Callable = "gaussian",
1575
+ bool signed=False,
1576
+ bool normalize=False, bool plot=False,
1577
+ bool save=False, int dpi=200,double p=2., box=None,
1578
+ bool flatten=False, int n_jobs=0,
1579
+ grid = None)->np.ndarray:
1580
+ r"""Computes a representation of the module, using
1581
+
1582
+ [A Framework for Fast and Stable Representations of Multiparameter Persistent Homology Decompositions, Neurips2023]
1583
+
1584
+ Parameters
1585
+ ----------
1586
+
1587
+ - degrees = None : integer list
1588
+ If given returns only the image(s) of homology degrees `degrees`.
1589
+ - bandwidth = 0.1 : float
1590
+ Image parameter.
1591
+ - resolution = [100,100] : pair of integers
1592
+ Resolution of the image(s).
1593
+ - normalize = True : Boolean
1594
+ Ensures that the image belongs to [0,1].
1595
+ - plot = False : Boolean
1596
+ If true, plots the images;
1597
+ - flatten=False :
1598
+ If True, reshapes the output to a flattened shape.
1599
+ - kernel: Either linear, gaussian, or callable
1600
+ The kernel to apply to the matrix $(d(x,I), x \in \mathrm{pixels}, I\in \mathrm{summands})$.
1601
+ signature should be : (distance matrix, summand_weights, bandwidth, p) -> representation
1602
+
1603
+ Returns
1604
+ -------
1605
+
1606
+ The list of images, or the image of fixed dimension.
1607
+ """
1608
+ import matplotlib.pyplot as plt
1609
+ # box = kwargs.get("box",[self.get_bottom(),self.get_top()])
1610
+ if box is None:
1611
+ box = self.get_box()
1612
+ num_parameters = self.num_parameters
1613
+ if degrees is None:
1614
+ degrees = np.arange(self.max_degree +1)
1615
+ num_degrees = len(degrees)
1616
+ try:
1617
+ int(resolution)
1618
+ resolution = [resolution]*num_parameters
1619
+ except:
1620
+ pass
1621
+
1622
+ if grid is None:
1623
+ grid = [np.linspace(*np.asarray(box)[:,parameter], num=res) for parameter, res in zip(range(num_parameters), resolution)]
1624
+ else:
1625
+ resolution = tuple(len(g) for g in grid)
1626
+ coordinates = mpg.todense(grid)
1627
+
1628
+ if kernel == "linear":
1629
+ assert not signed, "This kernel is not compatible with signed."
1630
+ concatenated_images = self._compute_pixels(coordinates, degrees=degrees, box=box, delta=bandwidth, p=p, normalize=normalize,n_jobs=n_jobs)
1631
+ else:
1632
+ if kernel == "linear2":
1633
+ def todo(PyModule_f32 mod_degree):
1634
+ x = mod_degree.distance_to(coordinates,signed=signed)
1635
+ w = mod_degree.get_interleavings()[None]**p
1636
+ s = np.where(x>=0,1,-1) if signed else 1
1637
+ x = np.abs(x)
1638
+ return (s*np.where(x<bandwidth,(bandwidth-x)/bandwidth,0)*w).sum(1)
1639
+ elif kernel == "gaussian":
1640
+ def todo(PyModule_f32 mod_degree):
1641
+ x = mod_degree.distance_to(coordinates,signed=signed)
1642
+ w = mod_degree.get_interleavings()[None]**p
1643
+ s = np.where(x>=0,1,-1) if signed else 1
1644
+ return (s*np.exp( -.5*((x/bandwidth)**2))*w).sum(1)
1645
+ elif kernel == "exponential":
1646
+ def todo(PyModule_f32 mod_degree):
1647
+ x = mod_degree.distance_to(coordinates,signed=signed)
1648
+ w = mod_degree.get_interleavings()[None]**p
1649
+ s = np.where(x>=0,1,-1) if signed else 1
1650
+ x = np.abs(x)
1651
+ return (s*np.exp( -((np.abs(x)/bandwidth)))*w).sum(1)
1652
+ else:
1653
+ assert callable(kernel), r"""
1654
+ Kernel should be
1655
+ gaussian, linear, linear2, exponential or callable,
1656
+ with signature
1657
+ (array[shape=(N, M)], array[shape=(M)])-> array(shape=(N)),
1658
+ the first argument being a distance matrix (pts) vs (summands of the module)
1659
+ and the second argument is a weight vector (weight(summand) for summand in module).
1660
+ Note that the distance can be signed.
1661
+ """
1662
+ def todo(PyModule_f32 mod_degree):
1663
+ x = mod_degree.distance_to(coordinates,signed=signed, n_jobs=n_jobs)
1664
+ w = mod_degree.get_interleavings()[None]**p
1665
+ return kernel(x/bandwidth,w)
1666
+ concatenated_images = np.stack(
1667
+ Parallel(n_jobs = n_jobs if n_jobs else -1, backend= "threading")(
1668
+ delayed(todo)(self.get_module_of_degree(degree))
1669
+ for degree in degrees
1670
+ )
1671
+ )
1672
+
1673
+ if flatten:
1674
+ image_vector = concatenated_images.reshape((len(degrees),-1))
1675
+ if plot:
1676
+ raise ValueError("Unflatten to plot.")
1677
+ return image_vector
1678
+ else:
1679
+ image_vector = concatenated_images.reshape((len(degrees),*resolution))
1680
+ if plot:
1681
+ assert num_parameters == 2, "Plot only available for 2-parameter modules"
1682
+ import multipers.plots
1683
+ i=0
1684
+ n_plots = len(image_vector)
1685
+ scale = 4
1686
+ if n_plots >1:
1687
+ fig, axs = plt.subplots(1,n_plots, figsize=(n_plots*scale,scale))
1688
+ else:
1689
+ fig = plt.gcf()
1690
+ axs = [plt.gca()]
1691
+ for image, degree, i in zip(image_vector, degrees, range(num_degrees)):
1692
+ ax = axs[i]
1693
+ temp = multipers.plots.plot_surface(grid, image.T, ax=ax)
1694
+ plt.colorbar(temp, ax = ax)
1695
+ if degree < 0 :
1696
+ ax.set_title(rf"$H_{i}$ $2$-persistence image")
1697
+ if degree >= 0:
1698
+ ax.set_title(rf"$H_{degree}$ $2$-persistence image")
1699
+ return image_vector
1700
+
1701
+ def euler_char(self, points:list|np.ndarray) -> np.ndarray:
1702
+ r""" Computes the Euler Characteristic of the filtered complex at given (multiparameter) time
1703
+
1704
+ Parameters
1705
+ ----------
1706
+
1707
+ points: list[float] | list[list[float]] | np.ndarray
1708
+ List of filtration values on which to compute the euler characteristic.
1709
+ WARNING FIXME : the points have to have the same dimension as the simplextree.
1710
+
1711
+ Returns
1712
+ -------
1713
+
1714
+ The list of euler characteristic values
1715
+ """
1716
+ if len(points) == 0:
1717
+ return []
1718
+ if type(points[0]) is float:
1719
+ points = [points]
1720
+ if type(points) is np.ndarray:
1721
+ assert len(points.shape) in [1,2]
1722
+ if len(points.shape) == 1:
1723
+ points = [points]
1724
+
1725
+ cdef float[:,:] points_view = np.asarray(points, dtype = np.float32)
1726
+ cdef vector[One_critical_filtration[float]] c_points = _py2v1c_f32(points_view)
1727
+ # cdef One_critical_filtration temp
1728
+ # for point in points:
1729
+ # temp.clear()
1730
+ # for truc in point:
1731
+ # temp.push_back(<float>(truc))
1732
+ # c_points.push_back(temp)
1733
+ cdef Module[float] c_mod = self.cmod
1734
+ with nogil:
1735
+ c_euler = c_mod.euler_curve(c_points)
1736
+ euler = c_euler
1737
+ return np.asarray(euler, dtype=int)
1738
+ def to_idx(self,grid):
1739
+ cdef vector[vector[float]] cgrid = grid
1740
+ cdef vector[vector[pair[vector[vector[int]],vector[vector[int]]]]] out
1741
+ with nogil:
1742
+ out = self.cmod.to_idx(cgrid)
1743
+ return tuple(tuple((np.asarray(I.first,dtype=np.int64), np.asarray(I.second, dtype=np.int64)) for I in Is_of_degree) for Is_of_degree in out)
1744
+
1745
+ @cython.wraparound(False)
1746
+ @cython.boundscheck(False)
1747
+ def to_flat_idx(self,grid):
1748
+ if len(self) == 0:
1749
+ return np.empty((2,0), dtype = np.int32), np.empty((0, self.num_parameters), dtype = np.int32), np.empty((0, self.num_parameters), dtype = np.int32)
1750
+ cdef vector[vector[float]] cgrid = grid
1751
+ cdef vector[vector[vector[int]]] out
1752
+ cdef int num_summands, num_births, num_deaths
1753
+ cdef int num_parameters = self.num_parameters
1754
+ with nogil:
1755
+ out = self.cmod.to_flat_idx(cgrid)
1756
+ num_summands = out[0][0].size()
1757
+ num_births = out[1].size()
1758
+ num_deaths = out[2].size()
1759
+ idx = np.empty((2, num_summands),dtype=np.int32 )
1760
+ births = np.empty((num_births,num_parameters),dtype=np.int32)
1761
+ deaths = np.empty((num_deaths,num_parameters),dtype=np.int32)
1762
+
1763
+ cdef int32_t[:,:] idx_view = idx
1764
+ cdef int32_t[:,:] births_view = births
1765
+ cdef int32_t[:,:] deaths_view = deaths
1766
+
1767
+ with nogil:
1768
+ for i in range(num_summands):
1769
+ idx_view[0,i] = out[0][0][i]
1770
+ idx_view[1,i] = out[0][1][i]
1771
+ for i in range(num_births):
1772
+ for j in range(num_parameters):
1773
+ births_view[i,j] = out[1][i][j]
1774
+ for i in range(num_deaths):
1775
+ for j in range(num_parameters):
1776
+ deaths_view[i,j] = out[2][i][j]
1777
+
1778
+ return idx, births,deaths
1779
+
1780
+ def distances_idx_to(self, pts, bool full=False, int n_jobs=1):
1781
+ pts = np.asarray(pts)
1782
+ if pts.ndim == 1:
1783
+ pts = pts[None]
1784
+ cdef vector[vector[float]] cpts = pts
1785
+ cdef vector[vector[vector[int]]] out
1786
+ with nogil:
1787
+ out = self.cmod.compute_distances_idx_to(cpts,full, n_jobs)
1788
+ return np.asarray(out, dtype=np.int32)
1789
+
1790
+ def distance_to(self, pts, bool signed=False, int n_jobs = 0)->np.ndarray:
1791
+ r"""
1792
+ Distance from a point to each summand's support.
1793
+ Signed distance is the distance to the boundary,
1794
+ with negative values inside the summands.
1795
+
1796
+ pts of shape (num_pts, num_parameters)
1797
+
1798
+ output shape : (num_pts,num_summands)
1799
+ """
1800
+ pts = np.asarray(pts)
1801
+ if pts.ndim == 1:
1802
+ pts = pts[None]
1803
+ assert pts.shape[-1] == self.num_parameters
1804
+ cdef vector[vector[float]] cpts = pts
1805
+ # cdef vector[vector[float]] out
1806
+ to_fill = np.empty(shape=(cpts.size(),len(self)), dtype = np.float32)
1807
+ cdef float[:,:] c_to_fill = to_fill
1808
+ cdef float* data_ptr = &c_to_fill[0,0]
1809
+ with nogil:
1810
+ self.cmod.compute_distances_to(data_ptr, cpts,signed, n_jobs)
1811
+ return to_fill
1812
+
1813
+ def get_interleavings(self,box=None):
1814
+ if box is None:
1815
+ box = self.get_box()
1816
+ cdef Box[float] cbox = Box[float](box)
1817
+ return np.asarray(self.cmod.get_interleavings(cbox))
1818
+
1819
+ cdef class PyMultiDiagramPoint_f32:
1820
+ cdef MultiDiagram_point[One_critical_filtration[float]] point
1821
+ cdef set(self, MultiDiagram_point[One_critical_filtration[float]] pt):
1822
+ self.point = pt
1823
+ return self
1824
+
1825
+ def get_degree(self):
1826
+ return self.point.get_dimension()
1827
+ def get_birth(self):
1828
+ cdef One_critical_filtration[float] v = self.point.get_birth()
1829
+ return _ff21cview_f32(&v, copy=True)
1830
+ def get_death(self):
1831
+ cdef One_critical_filtration[float] v = self.point.get_death()
1832
+ return _ff21cview_f32(&v, copy=True)
1833
+
1834
+
1835
+ cdef class PyMultiDiagram_f32:
1836
+ r"""
1837
+ Stores the diagram of a PyModule on a line
1838
+ """
1839
+ cdef MultiDiagram[One_critical_filtration[float], float] multiDiagram
1840
+ cdef set(self, MultiDiagram[One_critical_filtration[float], float] m):
1841
+ self.multiDiagram = m
1842
+ return self
1843
+ def get_points(self, degree:int=-1) -> np.ndarray:
1844
+ cdef vector[pair[vector[float],vector[float]]] out = self.multiDiagram.get_points(degree)
1845
+ if len(out) == 0 and len(self) == 0:
1846
+ return np.empty() # TODO Retrieve good number of parameters if there is no points in diagram
1847
+ if len(out) == 0:
1848
+ return np.empty((0,2,self.multiDiagram.at(0).get_dimension())) # gets the number of parameters
1849
+ return np.array(out)
1850
+ def to_multipers(self, dimension:int):
1851
+ return self.multiDiagram.to_multipers(dimension)
1852
+ def __len__(self) -> int:
1853
+ return self.multiDiagram.size()
1854
+ def __getitem__(self,i:int) -> PyMultiDiagramPoint_f32:
1855
+ return PyMultiDiagramPoint_f32().set(self.multiDiagram.at(i % self.multiDiagram.size()))
1856
+ cdef class PyMultiDiagrams_f32:
1857
+ """
1858
+ Stores the barcodes of a PyModule on multiple lines
1859
+ """
1860
+ cdef MultiDiagrams[One_critical_filtration[float], float] multiDiagrams
1861
+ cdef set(self,MultiDiagrams[One_critical_filtration[float], float] m):
1862
+ self.multiDiagrams = m
1863
+ return self
1864
+ def to_multipers(self):
1865
+ out = self.multiDiagrams.to_multipers()
1866
+ return [np.asarray(summand) for summand in out]
1867
+ def __getitem__(self,i:int):
1868
+ if i >=0 :
1869
+ return PyMultiDiagram_f32().set(self.multiDiagrams.at(i))
1870
+ else:
1871
+ return PyMultiDiagram_f32().set(self.multiDiagrams.at( self.multiDiagrams.size() - i))
1872
+ def __len__(self):
1873
+ return self.multiDiagrams.size()
1874
+ def get_points(self, degree:int=-1):
1875
+ return self.multiDiagrams.get_points()
1876
+ cdef _get_plot_bars(self, dimension:int=-1, min_persistence:float=0):
1877
+ return self.multiDiagrams._for_python_plot(dimension, min_persistence);
1878
+ def plot(self, degree:int=-1, min_persistence:float=0):
1879
+ """
1880
+ Plots the barcodes.
1881
+
1882
+ Parameters
1883
+ ----------
1884
+
1885
+ - degree:int=-1
1886
+ Only plots the bars of specified homology degree. Useful when the multidiagrams contains multiple dimenions
1887
+ - min_persistence:float=0
1888
+ Only plot bars of length greater than this value. Useful to reduce the time to plot.
1889
+
1890
+ Warning
1891
+ -------
1892
+
1893
+ If the barcodes are not thresholded, essential barcodes will not be displayed !
1894
+
1895
+ """
1896
+ from cycler import cycler
1897
+ import matplotlib
1898
+ import matplotlib.pyplot as plt
1899
+ if len(self) == 0: return
1900
+ _cmap = matplotlib.colormaps["Spectral"]
1901
+ multibarcodes_, colors = self._get_plot_bars(degree, min_persistence)
1902
+ n_summands = np.max(colors)+1 if len(colors)>0 else 1
1903
+
1904
+ plt.rc('axes', prop_cycle = cycler('color', [_cmap(i/n_summands) for i in colors]))
1905
+ return plt.plot(*multibarcodes_)
1906
+
1907
+
1908
+ cdef dump_summand_f32(Summand[float]& summand):
1909
+ cdef vector[One_critical_filtration[float]] births = summand.get_birth_list()
1910
+ cdef vector[One_critical_filtration[float]] deaths = summand.get_death_list()
1911
+ return (
1912
+ _vff21cview_f32(births, copy=True), ## copy as local variables
1913
+ _vff21cview_f32(deaths, copy=True),
1914
+ summand.get_dimension(),
1915
+ )
1916
+
1917
+ cdef inline Summand[float] summand_from_dump_f32(summand_dump):
1918
+ cdef vector[One_critical_filtration[float]] births = _py2v1c_f32(summand_dump[0])
1919
+ cdef vector[One_critical_filtration[float]] deaths = _py2v1c_f32(summand_dump[1])
1920
+ cdef int dim = summand_dump[2]
1921
+ return Summand[float](births,deaths,dim)
1922
+
1923
+ cdef dump_cmod_f32(Module[float]& mod):
1924
+ cdef Box[float] cbox = mod.get_box()
1925
+ cdef int dim = mod.get_dimension()
1926
+ cdef cnp.ndarray[float, ndim=1] bottom_corner = _ff21cview_f32(&cbox.get_lower_corner())
1927
+ cdef cnp.ndarray[float, ndim=1] top_corner = _ff21cview_f32(&cbox.get_upper_corner())
1928
+ box = np.asarray([bottom_corner, top_corner])
1929
+ summands = tuple(dump_summand_f32(summand) for summand in mod)
1930
+ return box, summands
1931
+
1932
+ cdef Module[float] cmod_from_dump_f32(module_dump):
1933
+ box = module_dump[0]
1934
+ summands = module_dump[1]
1935
+ cdef Module[float] out_module = Module[float]()
1936
+ out_module.set_box(Box[float](box))
1937
+ for i in range(len(summands)):
1938
+ out_module.add_summand(summand_from_dump_f32(summands[i]))
1939
+ return out_module
1940
+
1941
+
1942
+ def from_dump_f32(dump)->PyModule_f32:
1943
+ r"""Retrieves a PyModule from a previous dump.
1944
+
1945
+ Parameters
1946
+ ----------
1947
+
1948
+ dump: either the output of the dump function, or a file containing the output of a dump.
1949
+ The dumped module to retrieve
1950
+
1951
+ Returns
1952
+ -------
1953
+
1954
+ PyModule
1955
+ The retrieved module.
1956
+ """
1957
+ # TODO : optimize...
1958
+ mod = PyModule_f32()
1959
+ if type(dump) is str:
1960
+ dump = pickle.load(open(dump, "rb"))
1961
+ cdef Module[float] cmod = cmod_from_dump_f32(dump)
1962
+ mod.cmod = cmod
1963
+ return mod
1964
+
1965
+ cdef class PySummand_i32:
1966
+ r"""
1967
+ Stores a Summand of a PyModule
1968
+ """
1969
+ cdef Summand[int32_t] sum
1970
+
1971
+ def get_birth_list(self):
1972
+ cdef vector[One_critical_filtration[int32_t]] v = self.sum.get_birth_list()
1973
+ return _vff21cview_i32(v, copy = True, duplicate = self.num_parameters())
1974
+
1975
+ def get_death_list(self):
1976
+ cdef vector[One_critical_filtration[int32_t]] v = self.sum.get_death_list()
1977
+ return _vff21cview_i32(v, copy = True, duplicate = self.num_parameters())
1978
+ @property
1979
+ def degree(self)->int:
1980
+ return self.sum.get_dimension()
1981
+
1982
+ cdef set(self, Summand[int32_t]& summand):
1983
+ self.sum = summand
1984
+ return self
1985
+ def get_bounds(self):
1986
+ cdef pair[One_critical_filtration[int32_t],One_critical_filtration[int32_t]] cbounds
1987
+ with nogil:
1988
+ cbounds = self.sum.get_bounds().get_bounding_corners()
1989
+ return _ff21cview_i32(&cbounds.first).copy(), _ff21cview_i32(&cbounds.second).copy()
1990
+ @property
1991
+ def dtype(self):
1992
+ return np.int32
1993
+
1994
+ def num_parameters(self):
1995
+ cdef vector[One_critical_filtration[int32_t]] v = self.sum.get_birth_list()
1996
+ if v[0].is_finite():
1997
+ return v[0].num_parameters()
1998
+ v = self.sum.get_death_list()
1999
+ return v[0].num_parameters()
2000
+
2001
+ cdef inline get_summand_filtration_values_i32(Summand[int32_t] summand):
2002
+ r"""
2003
+ Returns a list (over parameter) of the filtrations values of this parameter.
2004
+ """
2005
+ cdef vector[One_critical_filtration[int32_t]] vb = summand.get_birth_list()
2006
+ cdef vector[One_critical_filtration[int32_t]] vd = summand.get_death_list()
2007
+
2008
+ if vb[0].is_finite():
2009
+ if vd[0].is_finite():
2010
+ pts = np.concatenate([_vff21cview_i32(vb, copy=True),
2011
+ _vff21cview_i32(vd, copy=True)],axis=0)
2012
+ else:
2013
+ pts = np.array(_vff21cview_i32(vb, copy=True))
2014
+ else:
2015
+ if vd[0].is_finite():
2016
+ pts = np.array(_vff21cview_i32(vd, copy=True))
2017
+ else:
2018
+ return []
2019
+
2020
+ num_parameters = pts.shape[1]
2021
+ out = [np.unique(pts[:,parameter]) for parameter in range(num_parameters)]
2022
+ out = [f[:-1] if f[-1] == np.inf else f for f in out]
2023
+ out = [f[1:] if f[0] == -np.inf else f for f in out]
2024
+ return out
2025
+
2026
+ cdef class PyBox_i32:
2027
+ cdef Box[int32_t] box
2028
+ def __cinit__(self, vector[int32_t]& bottomCorner, vector[int32_t]& topCorner):
2029
+ self.box = Box[int32_t](bottomCorner, topCorner)
2030
+ @property
2031
+ def num_parameters(self):
2032
+ cdef size_t dim = self.box.get_lower_corner().num_parameters()
2033
+ if dim == self.box.get_upper_corner().num_parameters(): return dim
2034
+ else: print("Bad box definition.")
2035
+ def contains(self, x):
2036
+ return self.box.contains(x)
2037
+ cdef set(self, Box[int32_t]& b):
2038
+ self.box = b
2039
+ return self
2040
+
2041
+ def get(self):
2042
+ return [<vector[int32_t]>self.box.get_lower_corner(), <vector[int32_t]>self.box.get_upper_corner()]
2043
+ def to_multipers(self):
2044
+ #assert (self.get_dimension() == 2) "Multipers only works in dimension 2 !"
2045
+ return np.array(self.get()).flatten(order = 'F')
2046
+ @property
2047
+ def dtype(self):
2048
+ return np.int32
2049
+
2050
+
2051
+
2052
+ cdef class PyModule_i32:
2053
+ r"""
2054
+ Stores a representation of a n-persistence module.
2055
+ """
2056
+ cdef Module[int32_t] cmod
2057
+
2058
+ @property
2059
+ def dtype(self):
2060
+ return np.int32
2061
+
2062
+ cdef set(self, Module[int32_t] m):
2063
+ self.cmod = m
2064
+ def merge(self, PyModule_i32 other, int dim=-1):
2065
+ r"""
2066
+ Merges two modules into one
2067
+ """
2068
+ cdef Module[int32_t] c_other = other.cmod
2069
+ with nogil:
2070
+ for summand in c_other:
2071
+ self.cmod.add_summand(summand, dim)
2072
+ return self
2073
+
2074
+ def _set_from_ptr(self, intptr_t module_ptr):
2075
+ r"""
2076
+ Copy module from a memory pointer. Unsafe.
2077
+ """
2078
+ self.cmod = move(dereference(<Module[int32_t]*>(module_ptr)))
2079
+ def set_box(self, PyBox_i32 pybox):
2080
+ cdef Box[int32_t] cbox = pybox.box
2081
+ with nogil:
2082
+ self.cmod.set_box(cbox)
2083
+ return self
2084
+ def get_module_of_degree(self, int degree)->PyModule_i32: # TODO : in c++ ?
2085
+ r"""
2086
+ Returns a copy of a module of fixed degree.
2087
+ """
2088
+ pmodule = PyModule_i32()
2089
+ cdef Box[int32_t] c_box = self.cmod.get_box()
2090
+ pmodule.cmod.set_box(c_box)
2091
+ with nogil:
2092
+ for summand in self.cmod:
2093
+ if summand.get_dimension() == degree:
2094
+ pmodule.cmod.add_summand(summand)
2095
+ return pmodule
2096
+ def get_module_of_degrees(self, degrees:Iterable[int])->PyModule_i32: # TODO : in c++ ?
2097
+ r"""
2098
+ Returns a copy of the summands of degrees in `degrees`
2099
+ """
2100
+ pmodule = PyModule_i32()
2101
+ cdef Box[int32_t] c_box = self.cmod.get_box()
2102
+ pmodule.cmod.set_box(c_box)
2103
+ cdef vector[int] cdegrees = degrees
2104
+ with nogil:
2105
+ for summand in self.cmod:
2106
+ for d in cdegrees:
2107
+ if d == summand.get_dimension():
2108
+ pmodule.cmod.add_summand(summand)
2109
+ return pmodule
2110
+ def __len__(self)->int:
2111
+ return self.cmod.size()
2112
+ def get_bottom(self)->np.ndarray:
2113
+ r"""
2114
+ Bottom of the box of the module
2115
+ """
2116
+ return np.asarray(<vector[int32_t]>(self.cmod.get_box().get_lower_corner()))
2117
+ def get_top(self)->np.ndarray:
2118
+ r"""
2119
+ Top of the box of the module
2120
+ """
2121
+ return np.asarray(<vector[int32_t]>(self.cmod.get_box().get_upper_corner()))
2122
+ def get_box(self)->np.ndarray:
2123
+ r"""
2124
+ Returns the current bounding box of the module.
2125
+ """
2126
+ return np.asarray([self.get_bottom(), self.get_top()])
2127
+ @property
2128
+ def max_degree(self)->int:
2129
+ r"""
2130
+ Returns the maximum degree of the module.
2131
+ """
2132
+ return self.cmod.get_dimension()
2133
+ @property
2134
+ def num_parameters(self)->int:
2135
+ cdef size_t dim = self.cmod.get_box().get_lower_corner().num_parameters()
2136
+ assert dim == self.cmod.get_box().get_upper_corner().num_parameters(), "Bad box definition, cannot infer num_parameters."
2137
+ return dim
2138
+ def dump(self, path:str|None=None):
2139
+ r"""
2140
+ Dumps the module into a pickle-able format.
2141
+
2142
+ Parameters
2143
+ ----------
2144
+
2145
+ path:str=None (optional) saves the pickled module in specified path
2146
+
2147
+ Returns
2148
+ -------
2149
+
2150
+ list of list, encoding the module, which can be retrieved with the function `from_dump`.
2151
+ """
2152
+ ## TODO : optimize, but not really used.
2153
+ return dump_cmod_i32(self.cmod)
2154
+ def __getstate__(self):
2155
+ return self.dump()
2156
+ def __setstate__(self,dump):
2157
+ cdef Module[int32_t] cmod = cmod_from_dump_i32(dump)
2158
+ self.cmod = cmod
2159
+ return
2160
+ def __getitem__(self, int i) -> PySummand_i32:
2161
+ if i == slice(None):
2162
+ return self
2163
+ summand = PySummand_i32()
2164
+ summand.set(self.cmod.at(i % self.cmod.size()))
2165
+ return summand
2166
+ def __iter__(self):
2167
+ cdef int num_summands = self.cmod.size()
2168
+ for i in range(num_summands):
2169
+ summand = PySummand_i32()
2170
+ summand.set(self.cmod.at(i)) ## hmm copy. maybe do summand from ptr
2171
+ yield summand
2172
+
2173
+ def get_bounds(self):
2174
+ r"""
2175
+ Computes bounds from the summands' bounds.
2176
+ Useful to change this' box.
2177
+ """
2178
+ cdef pair[One_critical_filtration[int32_t],One_critical_filtration[int32_t]] cbounds
2179
+ with nogil:
2180
+ cbounds = self.cmod.get_bounds().get_bounding_corners()
2181
+ return _ff21cview_i32(&cbounds.first).copy(), _ff21cview_i32(&cbounds.second).copy()
2182
+ def rescale(self,rescale_factors, int degree=-1):
2183
+ r"""
2184
+ Rescales the fitlration values of the summands by this rescaling vector.
2185
+ """
2186
+ cdef vector[int32_t] crescale_factors = rescale_factors
2187
+ with nogil:
2188
+ self.cmod.rescale(crescale_factors,degree)
2189
+ def translate(self,translation, int degree=-1):
2190
+ r"""
2191
+ Translates the module in the filtration space by this vector.
2192
+ """
2193
+ cdef vector[int32_t] ctranslation = translation
2194
+ with nogil:
2195
+ self.cmod.translate(ctranslation,degree)
2196
+
2197
+ def get_filtration_values(self, bool unique=True):
2198
+ r"""
2199
+ Retrieves all filtration values of the summands of the module.
2200
+
2201
+ Output format
2202
+ -------------
2203
+
2204
+ list of filtration values for parameter.
2205
+ """
2206
+ if len(self) ==0:
2207
+ return np.empty((self.num_parameters,0))
2208
+ values = tuple(tuple(stuff) if len(stuff:=get_summand_filtration_values_i32(summand)) == self.num_parameters else list(stuff) + [[]]*(self.num_parameters - len(stuff)) for summand in self.cmod)
2209
+ try:
2210
+ values = tuple(np.concatenate([
2211
+ f[parameter]
2212
+ for f in values
2213
+ ], axis=0) for parameter in range(self.num_parameters)
2214
+ )
2215
+ except:
2216
+ return values
2217
+ if unique:
2218
+ return [np.unique(f) for f in values]
2219
+ return values
2220
+
2221
+ def plot(self, int degree=-1,**kwargs)->None:
2222
+ r"""Shows the module on a plot. Each color corresponds to an apprimation summand of the module, and its shape corresponds to its support.
2223
+ Only works with 2-parameter modules.
2224
+
2225
+ Parameters
2226
+ ----------
2227
+ degree = -1 : integer
2228
+ If positive returns only the image of dimension `dimension`.
2229
+ box=None : of the form [[b_x,b_y], [d_x,d_y]] where b,d are the bottom and top corner of the rectangle.
2230
+ If non-None, will plot the module on this specific rectangle.
2231
+ min_persistence =0 : float
2232
+ Only plots the summand with a persistence above this threshold.
2233
+ separated=False : bool
2234
+ If true, plot each summand in a different plot.
2235
+ alpha=1 : float
2236
+ Transparancy parameter
2237
+ save = False : string
2238
+ if nontrivial, will save the figure at this path
2239
+
2240
+
2241
+ Returns
2242
+ -------
2243
+ The figure of the plot.
2244
+ """
2245
+ from multipers.plots import plot2d_PyModule
2246
+ import matplotlib.pyplot as plt
2247
+ box = kwargs.pop('box', self.get_box())
2248
+ if (len(box[0]) != 2):
2249
+ print("Filtration size :", len(box[0]), " != 2")
2250
+ return
2251
+ if(degree < 0):
2252
+ dims = np.unique(self.get_dimensions())
2253
+ separated = kwargs.pop("separated", False)
2254
+ ndim = len(dims)
2255
+ scale = kwargs.pop("scale", 4)
2256
+ if separated:
2257
+ fig = None
2258
+ axes = None
2259
+ elif ndim > 1:
2260
+ fig, axes = plt.subplots(1,ndim, figsize=(ndim*scale,scale))
2261
+ else:
2262
+ fig = plt.gcf()
2263
+ axes = [plt.gca()]
2264
+ for dim_idx in range(ndim):
2265
+ if not separated:
2266
+ plt.sca(axes[dim_idx])
2267
+ self.plot(dims[dim_idx],box=box, separated = separated, **kwargs)
2268
+ return
2269
+ corners = self.cmod.get_corners_of_dimension(degree)
2270
+ plot2d_PyModule(corners, box=box, dimension=degree, **kwargs)
2271
+ return
2272
+ def degree_splits(self):
2273
+ return np.asarray(self.cmod.get_degree_splits(), dtype=np.int64)
2274
+
2275
+
2276
+ cdef dump_summand_i32(Summand[int32_t]& summand):
2277
+ cdef vector[One_critical_filtration[int32_t]] births = summand.get_birth_list()
2278
+ cdef vector[One_critical_filtration[int32_t]] deaths = summand.get_death_list()
2279
+ return (
2280
+ _vff21cview_i32(births, copy=True), ## copy as local variables
2281
+ _vff21cview_i32(deaths, copy=True),
2282
+ summand.get_dimension(),
2283
+ )
2284
+
2285
+ cdef inline Summand[int32_t] summand_from_dump_i32(summand_dump):
2286
+ cdef vector[One_critical_filtration[int32_t]] births = _py2v1c_i32(summand_dump[0])
2287
+ cdef vector[One_critical_filtration[int32_t]] deaths = _py2v1c_i32(summand_dump[1])
2288
+ cdef int dim = summand_dump[2]
2289
+ return Summand[int32_t](births,deaths,dim)
2290
+
2291
+ cdef dump_cmod_i32(Module[int32_t]& mod):
2292
+ cdef Box[int32_t] cbox = mod.get_box()
2293
+ cdef int dim = mod.get_dimension()
2294
+ cdef cnp.ndarray[int32_t, ndim=1] bottom_corner = _ff21cview_i32(&cbox.get_lower_corner())
2295
+ cdef cnp.ndarray[int32_t, ndim=1] top_corner = _ff21cview_i32(&cbox.get_upper_corner())
2296
+ box = np.asarray([bottom_corner, top_corner])
2297
+ summands = tuple(dump_summand_i32(summand) for summand in mod)
2298
+ return box, summands
2299
+
2300
+ cdef Module[int32_t] cmod_from_dump_i32(module_dump):
2301
+ box = module_dump[0]
2302
+ summands = module_dump[1]
2303
+ cdef Module[int32_t] out_module = Module[int32_t]()
2304
+ out_module.set_box(Box[int32_t](box))
2305
+ for i in range(len(summands)):
2306
+ out_module.add_summand(summand_from_dump_i32(summands[i]))
2307
+ return out_module
2308
+
2309
+
2310
+ def from_dump_i32(dump)->PyModule_i32:
2311
+ r"""Retrieves a PyModule from a previous dump.
2312
+
2313
+ Parameters
2314
+ ----------
2315
+
2316
+ dump: either the output of the dump function, or a file containing the output of a dump.
2317
+ The dumped module to retrieve
2318
+
2319
+ Returns
2320
+ -------
2321
+
2322
+ PyModule
2323
+ The retrieved module.
2324
+ """
2325
+ # TODO : optimize...
2326
+ mod = PyModule_i32()
2327
+ if type(dump) is str:
2328
+ dump = pickle.load(open(dump, "rb"))
2329
+ cdef Module[int32_t] cmod = cmod_from_dump_i32(dump)
2330
+ mod.cmod = cmod
2331
+ return mod
2332
+
2333
+ cdef class PySummand_i64:
2334
+ r"""
2335
+ Stores a Summand of a PyModule
2336
+ """
2337
+ cdef Summand[int64_t] sum
2338
+
2339
+ def get_birth_list(self):
2340
+ cdef vector[One_critical_filtration[int64_t]] v = self.sum.get_birth_list()
2341
+ return _vff21cview_i64(v, copy = True, duplicate = self.num_parameters())
2342
+
2343
+ def get_death_list(self):
2344
+ cdef vector[One_critical_filtration[int64_t]] v = self.sum.get_death_list()
2345
+ return _vff21cview_i64(v, copy = True, duplicate = self.num_parameters())
2346
+ @property
2347
+ def degree(self)->int:
2348
+ return self.sum.get_dimension()
2349
+
2350
+ cdef set(self, Summand[int64_t]& summand):
2351
+ self.sum = summand
2352
+ return self
2353
+ def get_bounds(self):
2354
+ cdef pair[One_critical_filtration[int64_t],One_critical_filtration[int64_t]] cbounds
2355
+ with nogil:
2356
+ cbounds = self.sum.get_bounds().get_bounding_corners()
2357
+ return _ff21cview_i64(&cbounds.first).copy(), _ff21cview_i64(&cbounds.second).copy()
2358
+ @property
2359
+ def dtype(self):
2360
+ return np.int64
2361
+
2362
+ def num_parameters(self):
2363
+ cdef vector[One_critical_filtration[int64_t]] v = self.sum.get_birth_list()
2364
+ if v[0].is_finite():
2365
+ return v[0].num_parameters()
2366
+ v = self.sum.get_death_list()
2367
+ return v[0].num_parameters()
2368
+
2369
+ cdef inline get_summand_filtration_values_i64(Summand[int64_t] summand):
2370
+ r"""
2371
+ Returns a list (over parameter) of the filtrations values of this parameter.
2372
+ """
2373
+ cdef vector[One_critical_filtration[int64_t]] vb = summand.get_birth_list()
2374
+ cdef vector[One_critical_filtration[int64_t]] vd = summand.get_death_list()
2375
+
2376
+ if vb[0].is_finite():
2377
+ if vd[0].is_finite():
2378
+ pts = np.concatenate([_vff21cview_i64(vb, copy=True),
2379
+ _vff21cview_i64(vd, copy=True)],axis=0)
2380
+ else:
2381
+ pts = np.array(_vff21cview_i64(vb, copy=True))
2382
+ else:
2383
+ if vd[0].is_finite():
2384
+ pts = np.array(_vff21cview_i64(vd, copy=True))
2385
+ else:
2386
+ return []
2387
+
2388
+ num_parameters = pts.shape[1]
2389
+ out = [np.unique(pts[:,parameter]) for parameter in range(num_parameters)]
2390
+ out = [f[:-1] if f[-1] == np.inf else f for f in out]
2391
+ out = [f[1:] if f[0] == -np.inf else f for f in out]
2392
+ return out
2393
+
2394
+ cdef class PyBox_i64:
2395
+ cdef Box[int64_t] box
2396
+ def __cinit__(self, vector[int64_t]& bottomCorner, vector[int64_t]& topCorner):
2397
+ self.box = Box[int64_t](bottomCorner, topCorner)
2398
+ @property
2399
+ def num_parameters(self):
2400
+ cdef size_t dim = self.box.get_lower_corner().num_parameters()
2401
+ if dim == self.box.get_upper_corner().num_parameters(): return dim
2402
+ else: print("Bad box definition.")
2403
+ def contains(self, x):
2404
+ return self.box.contains(x)
2405
+ cdef set(self, Box[int64_t]& b):
2406
+ self.box = b
2407
+ return self
2408
+
2409
+ def get(self):
2410
+ return [<vector[int64_t]>self.box.get_lower_corner(), <vector[int64_t]>self.box.get_upper_corner()]
2411
+ def to_multipers(self):
2412
+ #assert (self.get_dimension() == 2) "Multipers only works in dimension 2 !"
2413
+ return np.array(self.get()).flatten(order = 'F')
2414
+ @property
2415
+ def dtype(self):
2416
+ return np.int64
2417
+
2418
+
2419
+
2420
+ cdef class PyModule_i64:
2421
+ r"""
2422
+ Stores a representation of a n-persistence module.
2423
+ """
2424
+ cdef Module[int64_t] cmod
2425
+
2426
+ @property
2427
+ def dtype(self):
2428
+ return np.int64
2429
+
2430
+ cdef set(self, Module[int64_t] m):
2431
+ self.cmod = m
2432
+ def merge(self, PyModule_i64 other, int dim=-1):
2433
+ r"""
2434
+ Merges two modules into one
2435
+ """
2436
+ cdef Module[int64_t] c_other = other.cmod
2437
+ with nogil:
2438
+ for summand in c_other:
2439
+ self.cmod.add_summand(summand, dim)
2440
+ return self
2441
+
2442
+ def _set_from_ptr(self, intptr_t module_ptr):
2443
+ r"""
2444
+ Copy module from a memory pointer. Unsafe.
2445
+ """
2446
+ self.cmod = move(dereference(<Module[int64_t]*>(module_ptr)))
2447
+ def set_box(self, PyBox_i64 pybox):
2448
+ cdef Box[int64_t] cbox = pybox.box
2449
+ with nogil:
2450
+ self.cmod.set_box(cbox)
2451
+ return self
2452
+ def get_module_of_degree(self, int degree)->PyModule_i64: # TODO : in c++ ?
2453
+ r"""
2454
+ Returns a copy of a module of fixed degree.
2455
+ """
2456
+ pmodule = PyModule_i64()
2457
+ cdef Box[int64_t] c_box = self.cmod.get_box()
2458
+ pmodule.cmod.set_box(c_box)
2459
+ with nogil:
2460
+ for summand in self.cmod:
2461
+ if summand.get_dimension() == degree:
2462
+ pmodule.cmod.add_summand(summand)
2463
+ return pmodule
2464
+ def get_module_of_degrees(self, degrees:Iterable[int])->PyModule_i64: # TODO : in c++ ?
2465
+ r"""
2466
+ Returns a copy of the summands of degrees in `degrees`
2467
+ """
2468
+ pmodule = PyModule_i64()
2469
+ cdef Box[int64_t] c_box = self.cmod.get_box()
2470
+ pmodule.cmod.set_box(c_box)
2471
+ cdef vector[int] cdegrees = degrees
2472
+ with nogil:
2473
+ for summand in self.cmod:
2474
+ for d in cdegrees:
2475
+ if d == summand.get_dimension():
2476
+ pmodule.cmod.add_summand(summand)
2477
+ return pmodule
2478
+ def __len__(self)->int:
2479
+ return self.cmod.size()
2480
+ def get_bottom(self)->np.ndarray:
2481
+ r"""
2482
+ Bottom of the box of the module
2483
+ """
2484
+ return np.asarray(<vector[int64_t]>(self.cmod.get_box().get_lower_corner()))
2485
+ def get_top(self)->np.ndarray:
2486
+ r"""
2487
+ Top of the box of the module
2488
+ """
2489
+ return np.asarray(<vector[int64_t]>(self.cmod.get_box().get_upper_corner()))
2490
+ def get_box(self)->np.ndarray:
2491
+ r"""
2492
+ Returns the current bounding box of the module.
2493
+ """
2494
+ return np.asarray([self.get_bottom(), self.get_top()])
2495
+ @property
2496
+ def max_degree(self)->int:
2497
+ r"""
2498
+ Returns the maximum degree of the module.
2499
+ """
2500
+ return self.cmod.get_dimension()
2501
+ @property
2502
+ def num_parameters(self)->int:
2503
+ cdef size_t dim = self.cmod.get_box().get_lower_corner().num_parameters()
2504
+ assert dim == self.cmod.get_box().get_upper_corner().num_parameters(), "Bad box definition, cannot infer num_parameters."
2505
+ return dim
2506
+ def dump(self, path:str|None=None):
2507
+ r"""
2508
+ Dumps the module into a pickle-able format.
2509
+
2510
+ Parameters
2511
+ ----------
2512
+
2513
+ path:str=None (optional) saves the pickled module in specified path
2514
+
2515
+ Returns
2516
+ -------
2517
+
2518
+ list of list, encoding the module, which can be retrieved with the function `from_dump`.
2519
+ """
2520
+ ## TODO : optimize, but not really used.
2521
+ return dump_cmod_i64(self.cmod)
2522
+ def __getstate__(self):
2523
+ return self.dump()
2524
+ def __setstate__(self,dump):
2525
+ cdef Module[int64_t] cmod = cmod_from_dump_i64(dump)
2526
+ self.cmod = cmod
2527
+ return
2528
+ def __getitem__(self, int i) -> PySummand_i64:
2529
+ if i == slice(None):
2530
+ return self
2531
+ summand = PySummand_i64()
2532
+ summand.set(self.cmod.at(i % self.cmod.size()))
2533
+ return summand
2534
+ def __iter__(self):
2535
+ cdef int num_summands = self.cmod.size()
2536
+ for i in range(num_summands):
2537
+ summand = PySummand_i64()
2538
+ summand.set(self.cmod.at(i)) ## hmm copy. maybe do summand from ptr
2539
+ yield summand
2540
+
2541
+ def get_bounds(self):
2542
+ r"""
2543
+ Computes bounds from the summands' bounds.
2544
+ Useful to change this' box.
2545
+ """
2546
+ cdef pair[One_critical_filtration[int64_t],One_critical_filtration[int64_t]] cbounds
2547
+ with nogil:
2548
+ cbounds = self.cmod.get_bounds().get_bounding_corners()
2549
+ return _ff21cview_i64(&cbounds.first).copy(), _ff21cview_i64(&cbounds.second).copy()
2550
+ def rescale(self,rescale_factors, int degree=-1):
2551
+ r"""
2552
+ Rescales the fitlration values of the summands by this rescaling vector.
2553
+ """
2554
+ cdef vector[int64_t] crescale_factors = rescale_factors
2555
+ with nogil:
2556
+ self.cmod.rescale(crescale_factors,degree)
2557
+ def translate(self,translation, int degree=-1):
2558
+ r"""
2559
+ Translates the module in the filtration space by this vector.
2560
+ """
2561
+ cdef vector[int64_t] ctranslation = translation
2562
+ with nogil:
2563
+ self.cmod.translate(ctranslation,degree)
2564
+
2565
+ def get_filtration_values(self, bool unique=True):
2566
+ r"""
2567
+ Retrieves all filtration values of the summands of the module.
2568
+
2569
+ Output format
2570
+ -------------
2571
+
2572
+ list of filtration values for parameter.
2573
+ """
2574
+ if len(self) ==0:
2575
+ return np.empty((self.num_parameters,0))
2576
+ values = tuple(tuple(stuff) if len(stuff:=get_summand_filtration_values_i64(summand)) == self.num_parameters else list(stuff) + [[]]*(self.num_parameters - len(stuff)) for summand in self.cmod)
2577
+ try:
2578
+ values = tuple(np.concatenate([
2579
+ f[parameter]
2580
+ for f in values
2581
+ ], axis=0) for parameter in range(self.num_parameters)
2582
+ )
2583
+ except:
2584
+ return values
2585
+ if unique:
2586
+ return [np.unique(f) for f in values]
2587
+ return values
2588
+
2589
+ def plot(self, int degree=-1,**kwargs)->None:
2590
+ r"""Shows the module on a plot. Each color corresponds to an apprimation summand of the module, and its shape corresponds to its support.
2591
+ Only works with 2-parameter modules.
2592
+
2593
+ Parameters
2594
+ ----------
2595
+ degree = -1 : integer
2596
+ If positive returns only the image of dimension `dimension`.
2597
+ box=None : of the form [[b_x,b_y], [d_x,d_y]] where b,d are the bottom and top corner of the rectangle.
2598
+ If non-None, will plot the module on this specific rectangle.
2599
+ min_persistence =0 : float
2600
+ Only plots the summand with a persistence above this threshold.
2601
+ separated=False : bool
2602
+ If true, plot each summand in a different plot.
2603
+ alpha=1 : float
2604
+ Transparancy parameter
2605
+ save = False : string
2606
+ if nontrivial, will save the figure at this path
2607
+
2608
+
2609
+ Returns
2610
+ -------
2611
+ The figure of the plot.
2612
+ """
2613
+ from multipers.plots import plot2d_PyModule
2614
+ import matplotlib.pyplot as plt
2615
+ box = kwargs.pop('box', self.get_box())
2616
+ if (len(box[0]) != 2):
2617
+ print("Filtration size :", len(box[0]), " != 2")
2618
+ return
2619
+ if(degree < 0):
2620
+ dims = np.unique(self.get_dimensions())
2621
+ separated = kwargs.pop("separated", False)
2622
+ ndim = len(dims)
2623
+ scale = kwargs.pop("scale", 4)
2624
+ if separated:
2625
+ fig = None
2626
+ axes = None
2627
+ elif ndim > 1:
2628
+ fig, axes = plt.subplots(1,ndim, figsize=(ndim*scale,scale))
2629
+ else:
2630
+ fig = plt.gcf()
2631
+ axes = [plt.gca()]
2632
+ for dim_idx in range(ndim):
2633
+ if not separated:
2634
+ plt.sca(axes[dim_idx])
2635
+ self.plot(dims[dim_idx],box=box, separated = separated, **kwargs)
2636
+ return
2637
+ corners = self.cmod.get_corners_of_dimension(degree)
2638
+ plot2d_PyModule(corners, box=box, dimension=degree, **kwargs)
2639
+ return
2640
+ def degree_splits(self):
2641
+ return np.asarray(self.cmod.get_degree_splits(), dtype=np.int64)
2642
+
2643
+
2644
+ cdef dump_summand_i64(Summand[int64_t]& summand):
2645
+ cdef vector[One_critical_filtration[int64_t]] births = summand.get_birth_list()
2646
+ cdef vector[One_critical_filtration[int64_t]] deaths = summand.get_death_list()
2647
+ return (
2648
+ _vff21cview_i64(births, copy=True), ## copy as local variables
2649
+ _vff21cview_i64(deaths, copy=True),
2650
+ summand.get_dimension(),
2651
+ )
2652
+
2653
+ cdef inline Summand[int64_t] summand_from_dump_i64(summand_dump):
2654
+ cdef vector[One_critical_filtration[int64_t]] births = _py2v1c_i64(summand_dump[0])
2655
+ cdef vector[One_critical_filtration[int64_t]] deaths = _py2v1c_i64(summand_dump[1])
2656
+ cdef int dim = summand_dump[2]
2657
+ return Summand[int64_t](births,deaths,dim)
2658
+
2659
+ cdef dump_cmod_i64(Module[int64_t]& mod):
2660
+ cdef Box[int64_t] cbox = mod.get_box()
2661
+ cdef int dim = mod.get_dimension()
2662
+ cdef cnp.ndarray[int64_t, ndim=1] bottom_corner = _ff21cview_i64(&cbox.get_lower_corner())
2663
+ cdef cnp.ndarray[int64_t, ndim=1] top_corner = _ff21cview_i64(&cbox.get_upper_corner())
2664
+ box = np.asarray([bottom_corner, top_corner])
2665
+ summands = tuple(dump_summand_i64(summand) for summand in mod)
2666
+ return box, summands
2667
+
2668
+ cdef Module[int64_t] cmod_from_dump_i64(module_dump):
2669
+ box = module_dump[0]
2670
+ summands = module_dump[1]
2671
+ cdef Module[int64_t] out_module = Module[int64_t]()
2672
+ out_module.set_box(Box[int64_t](box))
2673
+ for i in range(len(summands)):
2674
+ out_module.add_summand(summand_from_dump_i64(summands[i]))
2675
+ return out_module
2676
+
2677
+
2678
+ def from_dump_i64(dump)->PyModule_i64:
2679
+ r"""Retrieves a PyModule from a previous dump.
2680
+
2681
+ Parameters
2682
+ ----------
2683
+
2684
+ dump: either the output of the dump function, or a file containing the output of a dump.
2685
+ The dumped module to retrieve
2686
+
2687
+ Returns
2688
+ -------
2689
+
2690
+ PyModule
2691
+ The retrieved module.
2692
+ """
2693
+ # TODO : optimize...
2694
+ mod = PyModule_i64()
2695
+ if type(dump) is str:
2696
+ dump = pickle.load(open(dump, "rb"))
2697
+ cdef Module[int64_t] cmod = cmod_from_dump_i64(dump)
2698
+ mod.cmod = cmod
2699
+ return mod
2700
+
2701
+
2702
+
2703
+ global PyModule_type, PySummand_type
2704
+ PyModule_type = Union[
2705
+ PyModule_f64,
2706
+ PyModule_f32,
2707
+ PyModule_i32,
2708
+ PyModule_i64,
2709
+ ]
2710
+ PySummand_type = Union[
2711
+ PySummand_f64,
2712
+ PySummand_f32,
2713
+ PySummand_i32,
2714
+ PySummand_i64,
2715
+ ]
2716
+
2717
+ PyBox_type = Union[
2718
+ PyBox_f64,
2719
+ PyBox_f32,
2720
+ PyBox_i32,
2721
+ PyBox_i64,
2722
+ ]
2723
+
2724
+
2725
+ PyMultiDiagram_type = Union[
2726
+ PyMultiDiagram_f64,
2727
+ PyMultiDiagram_f32,
2728
+ ]
2729
+
2730
+
2731
+ PyMultiDiagrams_type = Union[
2732
+ PyMultiDiagrams_f64,
2733
+ PyMultiDiagrams_f32,
2734
+ ]
2735
+
2736
+ def is_mma(stuff):
2737
+ return (False
2738
+ or isinstance(stuff,PyModule_f64)
2739
+ or isinstance(stuff,PyModule_f32)
2740
+ or isinstance(stuff,PyModule_i32)
2741
+ or isinstance(stuff,PyModule_i64)
2742
+ )