multipers 2.2.3__cp312-cp312-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


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

Files changed (189) hide show
  1. multipers/__init__.py +31 -0
  2. multipers/_signed_measure_meta.py +430 -0
  3. multipers/_slicer_meta.py +212 -0
  4. multipers/data/MOL2.py +458 -0
  5. multipers/data/UCR.py +18 -0
  6. multipers/data/__init__.py +1 -0
  7. multipers/data/graphs.py +466 -0
  8. multipers/data/immuno_regions.py +27 -0
  9. multipers/data/minimal_presentation_to_st_bf.py +0 -0
  10. multipers/data/pytorch2simplextree.py +91 -0
  11. multipers/data/shape3d.py +101 -0
  12. multipers/data/synthetic.py +111 -0
  13. multipers/distances.py +198 -0
  14. multipers/filtration_conversions.pxd +229 -0
  15. multipers/filtration_conversions.pxd.tp +84 -0
  16. multipers/filtrations.pxd +224 -0
  17. multipers/function_rips.cp312-win_amd64.pyd +0 -0
  18. multipers/function_rips.pyx +105 -0
  19. multipers/grids.cp312-win_amd64.pyd +0 -0
  20. multipers/grids.pyx +350 -0
  21. multipers/gudhi/Persistence_slices_interface.h +132 -0
  22. multipers/gudhi/Simplex_tree_interface.h +245 -0
  23. multipers/gudhi/Simplex_tree_multi_interface.h +561 -0
  24. multipers/gudhi/cubical_to_boundary.h +59 -0
  25. multipers/gudhi/gudhi/Bitmap_cubical_complex.h +450 -0
  26. multipers/gudhi/gudhi/Bitmap_cubical_complex_base.h +1070 -0
  27. multipers/gudhi/gudhi/Bitmap_cubical_complex_periodic_boundary_conditions_base.h +579 -0
  28. multipers/gudhi/gudhi/Debug_utils.h +45 -0
  29. multipers/gudhi/gudhi/Fields/Multi_field.h +484 -0
  30. multipers/gudhi/gudhi/Fields/Multi_field_operators.h +455 -0
  31. multipers/gudhi/gudhi/Fields/Multi_field_shared.h +450 -0
  32. multipers/gudhi/gudhi/Fields/Multi_field_small.h +531 -0
  33. multipers/gudhi/gudhi/Fields/Multi_field_small_operators.h +507 -0
  34. multipers/gudhi/gudhi/Fields/Multi_field_small_shared.h +531 -0
  35. multipers/gudhi/gudhi/Fields/Z2_field.h +355 -0
  36. multipers/gudhi/gudhi/Fields/Z2_field_operators.h +376 -0
  37. multipers/gudhi/gudhi/Fields/Zp_field.h +420 -0
  38. multipers/gudhi/gudhi/Fields/Zp_field_operators.h +400 -0
  39. multipers/gudhi/gudhi/Fields/Zp_field_shared.h +418 -0
  40. multipers/gudhi/gudhi/Flag_complex_edge_collapser.h +337 -0
  41. multipers/gudhi/gudhi/Matrix.h +2107 -0
  42. multipers/gudhi/gudhi/Multi_critical_filtration.h +1038 -0
  43. multipers/gudhi/gudhi/Multi_persistence/Box.h +171 -0
  44. multipers/gudhi/gudhi/Multi_persistence/Line.h +282 -0
  45. multipers/gudhi/gudhi/Off_reader.h +173 -0
  46. multipers/gudhi/gudhi/One_critical_filtration.h +1431 -0
  47. multipers/gudhi/gudhi/Persistence_matrix/Base_matrix.h +769 -0
  48. multipers/gudhi/gudhi/Persistence_matrix/Base_matrix_with_column_compression.h +686 -0
  49. multipers/gudhi/gudhi/Persistence_matrix/Boundary_matrix.h +842 -0
  50. multipers/gudhi/gudhi/Persistence_matrix/Chain_matrix.h +1350 -0
  51. multipers/gudhi/gudhi/Persistence_matrix/Id_to_index_overlay.h +1105 -0
  52. multipers/gudhi/gudhi/Persistence_matrix/Position_to_index_overlay.h +859 -0
  53. multipers/gudhi/gudhi/Persistence_matrix/RU_matrix.h +910 -0
  54. multipers/gudhi/gudhi/Persistence_matrix/allocators/entry_constructors.h +139 -0
  55. multipers/gudhi/gudhi/Persistence_matrix/base_pairing.h +230 -0
  56. multipers/gudhi/gudhi/Persistence_matrix/base_swap.h +211 -0
  57. multipers/gudhi/gudhi/Persistence_matrix/boundary_cell_position_to_id_mapper.h +60 -0
  58. multipers/gudhi/gudhi/Persistence_matrix/boundary_face_position_to_id_mapper.h +60 -0
  59. multipers/gudhi/gudhi/Persistence_matrix/chain_pairing.h +136 -0
  60. multipers/gudhi/gudhi/Persistence_matrix/chain_rep_cycles.h +190 -0
  61. multipers/gudhi/gudhi/Persistence_matrix/chain_vine_swap.h +616 -0
  62. multipers/gudhi/gudhi/Persistence_matrix/columns/chain_column_extra_properties.h +150 -0
  63. multipers/gudhi/gudhi/Persistence_matrix/columns/column_dimension_holder.h +106 -0
  64. multipers/gudhi/gudhi/Persistence_matrix/columns/column_utilities.h +219 -0
  65. multipers/gudhi/gudhi/Persistence_matrix/columns/entry_types.h +327 -0
  66. multipers/gudhi/gudhi/Persistence_matrix/columns/heap_column.h +1140 -0
  67. multipers/gudhi/gudhi/Persistence_matrix/columns/intrusive_list_column.h +934 -0
  68. multipers/gudhi/gudhi/Persistence_matrix/columns/intrusive_set_column.h +934 -0
  69. multipers/gudhi/gudhi/Persistence_matrix/columns/list_column.h +980 -0
  70. multipers/gudhi/gudhi/Persistence_matrix/columns/naive_vector_column.h +1092 -0
  71. multipers/gudhi/gudhi/Persistence_matrix/columns/row_access.h +192 -0
  72. multipers/gudhi/gudhi/Persistence_matrix/columns/set_column.h +921 -0
  73. multipers/gudhi/gudhi/Persistence_matrix/columns/small_vector_column.h +1093 -0
  74. multipers/gudhi/gudhi/Persistence_matrix/columns/unordered_set_column.h +1012 -0
  75. multipers/gudhi/gudhi/Persistence_matrix/columns/vector_column.h +1244 -0
  76. multipers/gudhi/gudhi/Persistence_matrix/matrix_dimension_holders.h +186 -0
  77. multipers/gudhi/gudhi/Persistence_matrix/matrix_row_access.h +164 -0
  78. multipers/gudhi/gudhi/Persistence_matrix/ru_pairing.h +156 -0
  79. multipers/gudhi/gudhi/Persistence_matrix/ru_rep_cycles.h +376 -0
  80. multipers/gudhi/gudhi/Persistence_matrix/ru_vine_swap.h +540 -0
  81. multipers/gudhi/gudhi/Persistent_cohomology/Field_Zp.h +118 -0
  82. multipers/gudhi/gudhi/Persistent_cohomology/Multi_field.h +173 -0
  83. multipers/gudhi/gudhi/Persistent_cohomology/Persistent_cohomology_column.h +128 -0
  84. multipers/gudhi/gudhi/Persistent_cohomology.h +745 -0
  85. multipers/gudhi/gudhi/Points_off_io.h +171 -0
  86. multipers/gudhi/gudhi/Simple_object_pool.h +69 -0
  87. multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_iterators.h +463 -0
  88. multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_node_explicit_storage.h +83 -0
  89. multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_siblings.h +106 -0
  90. multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_star_simplex_iterators.h +277 -0
  91. multipers/gudhi/gudhi/Simplex_tree/hooks_simplex_base.h +62 -0
  92. multipers/gudhi/gudhi/Simplex_tree/indexing_tag.h +27 -0
  93. multipers/gudhi/gudhi/Simplex_tree/serialization_utils.h +62 -0
  94. multipers/gudhi/gudhi/Simplex_tree/simplex_tree_options.h +157 -0
  95. multipers/gudhi/gudhi/Simplex_tree.h +2794 -0
  96. multipers/gudhi/gudhi/Simplex_tree_multi.h +163 -0
  97. multipers/gudhi/gudhi/distance_functions.h +62 -0
  98. multipers/gudhi/gudhi/graph_simplicial_complex.h +104 -0
  99. multipers/gudhi/gudhi/persistence_interval.h +253 -0
  100. multipers/gudhi/gudhi/persistence_matrix_options.h +170 -0
  101. multipers/gudhi/gudhi/reader_utils.h +367 -0
  102. multipers/gudhi/mma_interface_coh.h +255 -0
  103. multipers/gudhi/mma_interface_h0.h +231 -0
  104. multipers/gudhi/mma_interface_matrix.h +282 -0
  105. multipers/gudhi/naive_merge_tree.h +575 -0
  106. multipers/gudhi/scc_io.h +289 -0
  107. multipers/gudhi/truc.h +888 -0
  108. multipers/io.cp312-win_amd64.pyd +0 -0
  109. multipers/io.pyx +711 -0
  110. multipers/ml/__init__.py +0 -0
  111. multipers/ml/accuracies.py +90 -0
  112. multipers/ml/convolutions.py +520 -0
  113. multipers/ml/invariants_with_persistable.py +79 -0
  114. multipers/ml/kernels.py +176 -0
  115. multipers/ml/mma.py +714 -0
  116. multipers/ml/one.py +472 -0
  117. multipers/ml/point_clouds.py +346 -0
  118. multipers/ml/signed_measures.py +1589 -0
  119. multipers/ml/sliced_wasserstein.py +461 -0
  120. multipers/ml/tools.py +113 -0
  121. multipers/mma_structures.cp312-win_amd64.pyd +0 -0
  122. multipers/mma_structures.pxd +127 -0
  123. multipers/mma_structures.pyx +2746 -0
  124. multipers/mma_structures.pyx.tp +1085 -0
  125. multipers/multi_parameter_rank_invariant/diff_helpers.h +93 -0
  126. multipers/multi_parameter_rank_invariant/euler_characteristic.h +97 -0
  127. multipers/multi_parameter_rank_invariant/function_rips.h +322 -0
  128. multipers/multi_parameter_rank_invariant/hilbert_function.h +769 -0
  129. multipers/multi_parameter_rank_invariant/persistence_slices.h +148 -0
  130. multipers/multi_parameter_rank_invariant/rank_invariant.h +369 -0
  131. multipers/multiparameter_edge_collapse.py +41 -0
  132. multipers/multiparameter_module_approximation/approximation.h +2295 -0
  133. multipers/multiparameter_module_approximation/combinatory.h +129 -0
  134. multipers/multiparameter_module_approximation/debug.h +107 -0
  135. multipers/multiparameter_module_approximation/euler_curves.h +0 -0
  136. multipers/multiparameter_module_approximation/format_python-cpp.h +286 -0
  137. multipers/multiparameter_module_approximation/heap_column.h +238 -0
  138. multipers/multiparameter_module_approximation/images.h +79 -0
  139. multipers/multiparameter_module_approximation/list_column.h +174 -0
  140. multipers/multiparameter_module_approximation/list_column_2.h +232 -0
  141. multipers/multiparameter_module_approximation/ru_matrix.h +347 -0
  142. multipers/multiparameter_module_approximation/set_column.h +135 -0
  143. multipers/multiparameter_module_approximation/structure_higher_dim_barcode.h +36 -0
  144. multipers/multiparameter_module_approximation/unordered_set_column.h +166 -0
  145. multipers/multiparameter_module_approximation/utilities.h +419 -0
  146. multipers/multiparameter_module_approximation/vector_column.h +223 -0
  147. multipers/multiparameter_module_approximation/vector_matrix.h +331 -0
  148. multipers/multiparameter_module_approximation/vineyards.h +464 -0
  149. multipers/multiparameter_module_approximation/vineyards_trajectories.h +649 -0
  150. multipers/multiparameter_module_approximation.cp312-win_amd64.pyd +0 -0
  151. multipers/multiparameter_module_approximation.pyx +217 -0
  152. multipers/pickle.py +53 -0
  153. multipers/plots.py +334 -0
  154. multipers/point_measure.cp312-win_amd64.pyd +0 -0
  155. multipers/point_measure.pyx +320 -0
  156. multipers/simplex_tree_multi.cp312-win_amd64.pyd +0 -0
  157. multipers/simplex_tree_multi.pxd +133 -0
  158. multipers/simplex_tree_multi.pyx +10335 -0
  159. multipers/simplex_tree_multi.pyx.tp +1935 -0
  160. multipers/slicer.cp312-win_amd64.pyd +0 -0
  161. multipers/slicer.pxd +2371 -0
  162. multipers/slicer.pxd.tp +214 -0
  163. multipers/slicer.pyx +15467 -0
  164. multipers/slicer.pyx.tp +914 -0
  165. multipers/tbb12.dll +0 -0
  166. multipers/tbbbind_2_5.dll +0 -0
  167. multipers/tbbmalloc.dll +0 -0
  168. multipers/tbbmalloc_proxy.dll +0 -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/tests/test_diff_helper.py +73 -0
  174. multipers/tests/test_hilbert_function.py +82 -0
  175. multipers/tests/test_mma.py +83 -0
  176. multipers/tests/test_point_clouds.py +49 -0
  177. multipers/tests/test_python-cpp_conversion.py +82 -0
  178. multipers/tests/test_signed_betti.py +181 -0
  179. multipers/tests/test_signed_measure.py +89 -0
  180. multipers/tests/test_simplextreemulti.py +221 -0
  181. multipers/tests/test_slicer.py +221 -0
  182. multipers/torch/__init__.py +1 -0
  183. multipers/torch/diff_grids.py +217 -0
  184. multipers/torch/rips_density.py +304 -0
  185. multipers-2.2.3.dist-info/LICENSE +21 -0
  186. multipers-2.2.3.dist-info/METADATA +134 -0
  187. multipers-2.2.3.dist-info/RECORD +189 -0
  188. multipers-2.2.3.dist-info/WHEEL +5 -0
  189. multipers-2.2.3.dist-info/top_level.txt +1 -0
multipers/io.pyx ADDED
@@ -0,0 +1,711 @@
1
+ import re
2
+ from gudhi import SimplexTree
3
+ import multipers.slicer as mps
4
+ import gudhi as gd
5
+ import numpy as np
6
+ import os
7
+ from shutil import which
8
+ from libcpp cimport bool
9
+ from typing import Optional, Literal
10
+ from collections import defaultdict
11
+ import itertools
12
+ import threading
13
+ import cython
14
+ cimport cython
15
+
16
+ # from multipers.filtration_conversions cimport *
17
+ # from multipers.mma_structures cimport boundary_matrix,float,pair,vector,intptr_t
18
+ # cimport numpy as cnp
19
+
20
+ doc_soft_urls = {
21
+ "mpfree":"https://bitbucket.org/mkerber/mpfree/",
22
+ "multi_chunk":"",
23
+ "function_delaunay":"https://bitbucket.org/mkerber/function_delaunay/",
24
+ "2pac":"https://gitlab.com/flenzen/2pac",
25
+ }
26
+ doc_soft_easy_install = {
27
+ "mpfree":f"""
28
+ ```sh
29
+ git clone {doc_soft_urls["mpfree"]}
30
+ cd mpfree
31
+ sudo cp mpfree /usr/bin/
32
+ cd ..
33
+ rm -rf mpfree
34
+ ```
35
+ """,
36
+ "multi_chunk":f"""
37
+ ```sh
38
+ git clone {doc_soft_urls["multi_chunk"]}
39
+ cd multi_chunk
40
+ sudo cp multi_chunk /usr/bin/
41
+ cd ..
42
+ rm -rf multi_chunk
43
+ ```
44
+ """,
45
+ "function_delaunay":f"""
46
+ ```sh
47
+ git clone {doc_soft_urls["function_delaunay"]}
48
+ cd function_delaunay
49
+ sudo cp main /usr/bin/function_delaunay
50
+ cd ..
51
+ rm -rf function_delaunay
52
+ ```
53
+ """,
54
+ "2pac":f"""
55
+ ```sh
56
+ git clone {doc_soft_urls["2pac"]} 2pac
57
+ cd 2pac && mkdir build && cd build
58
+ cmake ..
59
+ make
60
+ sudo cp 2pac /usr/bin
61
+ ```
62
+ """,
63
+ }
64
+ doc_soft_urls = defaultdict(lambda:"<Unknown url>", doc_soft_urls)
65
+ doc_soft_easy_install = defaultdict(lambda:"<Unknown>", doc_soft_easy_install)
66
+
67
+ available_reduce_softs = Literal["mpfree","multi_chunk","2pac"]
68
+
69
+
70
+ def _path_init(soft:str|os.PathLike):
71
+ a = which(f"./{soft}")
72
+ b = which(f"{soft}")
73
+ if a:
74
+ pathes[soft] = a
75
+ elif b:
76
+ pathes[soft] = b
77
+
78
+ if pathes[soft] is not None:
79
+ verbose_arg = "> /dev/null 2>&1"
80
+ test = os.system(pathes[soft] + " --help " + verbose_arg)
81
+ if test:
82
+ from warnings import warn
83
+ warn(f"""
84
+ Found external software {soft} at {pathes[soft]}
85
+ but may not behave well.
86
+ """)
87
+
88
+
89
+
90
+ cdef dict[str,str|None] pathes = {
91
+ "mpfree":None,
92
+ "2pac":None,
93
+ "function_delaunay":None,
94
+ "multi_chunk":None,
95
+ }
96
+
97
+ # mpfree_in_path:str|os.PathLike = "multipers_mpfree_input.scc"
98
+ # mpfree_out_path:str|os.PathLike = "multipers_mpfree_output.scc"
99
+ # twopac_in_path:str|os.PathLike = "multipers_twopac_input.scc"
100
+ # twopac_out_path:str|os.PathLike = "multipers_twopac_output.scc"
101
+ # multi_chunk_in_path:str|os.PathLike = "multipers_multi_chunk_input.scc"
102
+ # multi_chunk_out_path:str|os.PathLike = "multipers_multi_chunk_output.scc"
103
+ # function_delaunay_out_path:str|os.PathLike = "function_delaunay_output.scc"
104
+ # function_delaunay_in_path:str|os.PathLike = "function_delaunay_input.txt" # point cloud
105
+ input_path:str|os.PathLike = "multipers_input.scc"
106
+ output_path:str|os.PathLike = "multipers_output.scc"
107
+
108
+
109
+
110
+ ## TODO : optimize with Python.h ?
111
+ def scc_parser(path: str| os.PathLike):
112
+ """
113
+ Parse an scc file into the scc python format, aka blocks.
114
+ """
115
+ pass_line_regex = re.compile(r"^\s*$|^#|^scc2020$")
116
+ def valid_line(line):
117
+ return pass_line_regex.match(line) is None
118
+ parse_line_regex = re.compile(r"^(?P<filtration>[^;]+);(?P<boundary>[^;]*)$")
119
+ cdef tuple[tuple[str,str]] clines
120
+ with open(path, "r") as f:
121
+ lines =(x.strip() for x in f if valid_line(x))
122
+ num_parameters = int(next(lines))
123
+ sizes = np.cumsum(np.asarray([0] + next(lines).split(), dtype=np.int32))
124
+ lines = (parse_line_regex.match(a) for a in lines)
125
+ clines = tuple((a.group("filtration"),a.group("boundary")) for a in lines)
126
+ # F = np.fromiter((a[0].split() for a in clines), dtype=np.dtype((np.float64,2)), count = sizes[-1])
127
+ F = np.fromiter((np.fromstring(a[0], sep=r' ', dtype=np.float64) for a in clines), dtype=np.dtype((np.float64,num_parameters)), count = sizes[-1])
128
+
129
+ # B = tuple(np.asarray(a[1].split(), dtype=np.int32) if len(a[1])>0 else np.empty(0, dtype=np.int32) for a in clines) ## TODO : this is very slow : optimize
130
+ B = tuple(np.fromstring(a[1], sep=' ', dtype=np.int32) for a in clines)
131
+ # block_lines = (tuple(get_bf(x, num_parameters) for x in lines[sizes[i]:sizes[i+1]]) for i in range(len(sizes)-1))
132
+
133
+ # blocks = [(np.asarray([x[0] for x in b if len(x)>0], dtype=float),tuple(x[1] for x in b)) for b in block_lines]
134
+ blocks = [(F[sizes[i]:sizes[i+1]], B[sizes[i]:sizes[i+1]]) for i in range(len(sizes)-1)]
135
+
136
+ return blocks
137
+
138
+
139
+ def scc_parser__old(path: str):
140
+ """
141
+ Parse an scc file into the scc python format, aka blocks.
142
+ """
143
+ with open(path, "r") as f:
144
+ lines = f.readlines()
145
+ # Find scc2020
146
+ while lines[0].strip() != "scc2020":
147
+ lines = lines[1:]
148
+ lines = lines[1:]
149
+ # stripped scc2020 we can start
150
+
151
+ def pass_line(line):
152
+ return re.match(r"^\s*$|^#", line) is not None
153
+
154
+ for i, line in enumerate(lines):
155
+ line = line.strip()
156
+ if pass_line(line):
157
+ continue
158
+ num_parameters = int(line)
159
+ lines = lines[i + 1 :]
160
+ break
161
+
162
+ block_sizes = []
163
+
164
+ for i, line in enumerate(lines):
165
+ line = line.strip()
166
+ if pass_line(line):
167
+ continue
168
+ block_sizes = tuple(int(i) for i in line.split(" "))
169
+ lines = lines[i + 1 :]
170
+ break
171
+ blocks = []
172
+ cdef int counter
173
+ for block_size in block_sizes:
174
+ counter = block_size
175
+ block_filtrations = []
176
+ block_boundaries = []
177
+ for i, line in enumerate(lines):
178
+ if counter == 0:
179
+ lines = lines[i:]
180
+ break
181
+ line = line.strip()
182
+ if pass_line(line):
183
+ continue
184
+ splitted_line = re.match(r"^(?P<floats>[^;]+);(?P<ints>[^;]*)$", line)
185
+ filtrations = np.asarray(splitted_line.group("floats").split(), dtype=float)
186
+ boundary = np.asarray(splitted_line.group("ints").split(), dtype=int)
187
+ block_filtrations.append(filtrations)
188
+ block_boundaries.append(boundary)
189
+ # filtration_boundary = line.split(";")
190
+ # if len(filtration_boundary) == 1:
191
+ # # happens when last generators do not have a ";" in the end
192
+ # filtration_boundary.append(" ")
193
+ # filtration, boundary = filtration_boundary
194
+ # block_filtrations.append(
195
+ # tuple(float(x) for x in filtration.split(" ") if len(x) > 0)
196
+ # )
197
+ # block_boundaries.append(tuple(int(x) for x in boundary.split(" ") if len(x) > 0))
198
+ counter -= 1
199
+ blocks.append((np.asarray(block_filtrations, dtype=float), tuple(block_boundaries)))
200
+
201
+ return blocks
202
+
203
+
204
+
205
+ def _put_temp_files_to_ram():
206
+ global input_path,output_path
207
+ shm_memory = "/tmp/" # on unix, we can write in RAM instead of disk.
208
+ if os.access(shm_memory, os.W_OK) and not input_path.startswith(shm_memory):
209
+ input_path = shm_memory + input_path
210
+ output_path = shm_memory + output_path
211
+
212
+ def _init_external_softwares(requires=[]):
213
+ global pathes
214
+ cdef bool any = False
215
+ for soft,soft_path in pathes.items():
216
+ if soft_path is None:
217
+ _path_init(soft)
218
+ any = any or (soft in requires)
219
+
220
+ if any:
221
+ _put_temp_files_to_ram()
222
+ for soft in requires:
223
+ if pathes[soft] is None:
224
+ global doc_soft_urls
225
+ raise ValueError(f"""
226
+ Did not found {soft}.
227
+ Install it from {doc_soft_urls[soft]}, and put it in your current directory,
228
+ or in you $PATH.
229
+ For instance:
230
+ {doc_soft_easy_install[soft]}
231
+ """)
232
+ def _check_available(soft:str):
233
+ _init_external_softwares()
234
+ return pathes.get(soft,None) is not None
235
+
236
+
237
+ def scc_reduce_from_str(
238
+ path:str|os.PathLike,
239
+ bool full_resolution=True,
240
+ int dimension: int | np.int64 = 1,
241
+ bool clear: bool = True,
242
+ id: Optional[str] = None, # For parallel stuff
243
+ bool verbose:bool=False,
244
+ backend:Literal["mpfree","multi_chunk","twopac"]="mpfree"
245
+ ):
246
+ """
247
+ Computes a minimal presentation of the file in path,
248
+ using mpfree.
249
+
250
+ path:PathLike
251
+ full_resolution: bool
252
+ dimension: int, presentation dimension to consider
253
+ clear: bool, removes temporary files if True
254
+ id: str, temporary files are of this id, allowing for multiprocessing
255
+ verbose: bool
256
+ backend: "mpfree", "multi_chunk" or "2pac"
257
+ """
258
+ global pathes, input_path, output_path
259
+ if pathes[backend] is None:
260
+ _init_external_softwares(requires=[backend])
261
+
262
+
263
+ resolution_str = "--resolution" if full_resolution else ""
264
+ # print(mpfree_in_path + id, mpfree_out_path + id)
265
+ if id is None:
266
+ id = str(threading.get_native_id())
267
+ if not os.path.exists(path):
268
+ raise ValueError(f"No file found at {path}.")
269
+ if os.path.exists(output_path + id):
270
+ os.remove(output_path + id)
271
+ verbose_arg = "> /dev/null 2>&1" if not verbose else ""
272
+ if backend == "mpfree":
273
+ more_verbose = "-v" if verbose else ""
274
+ command = (
275
+ f"{pathes[backend]} {more_verbose} {resolution_str} --dim={dimension} {path} {output_path+id} {verbose_arg}"
276
+ )
277
+ elif backend == "multi_chunk":
278
+ command = (
279
+ f"{pathes[backend]} {path} {output_path+id} {verbose_arg}"
280
+ )
281
+ elif backend in ["twopac", "2pac"]:
282
+ command = (
283
+ f"{pathes[backend]} -f {path} --scc-input -n{dimension} --save-resolution-scc {output_path+id} {verbose_arg}"
284
+ )
285
+ else:
286
+ raise ValueError(f"Unsupported backend {backend}.")
287
+ if verbose:
288
+ print(f"Calling :\n\n {command}")
289
+ os.system(command)
290
+
291
+ blocks = scc_parser(output_path + id)
292
+ if clear:
293
+ clear_io(input_path+id, output_path + id)
294
+
295
+
296
+ ## mpfree workaround: last size is 0 but shouldn't...
297
+ if len(blocks) and not len(blocks[-1][1]):
298
+ blocks=blocks[:-1]
299
+
300
+ return blocks
301
+
302
+ def scc_reduce_from_str_to_slicer(
303
+ path:str|os.PathLike,
304
+ slicer,
305
+ bool full_resolution=True,
306
+ int dimension: int | np.int64 = 1,
307
+ bool clear: bool = True,
308
+ id: Optional[str] = None, # For parallel stuff
309
+ bool verbose:bool=False,
310
+ backend:Literal["mpfree","multi_chunk","twopac"]="mpfree",
311
+ shift_dimension=0
312
+ ):
313
+ """
314
+ Computes a minimal presentation of the file in path,
315
+ using mpfree.
316
+
317
+ path:PathLike
318
+ slicer: empty slicer to fill
319
+ full_resolution: bool
320
+ dimension: int, presentation dimension to consider
321
+ clear: bool, removes temporary files if True
322
+ id: str, temporary files are of this id, allowing for multiprocessing
323
+ verbose: bool
324
+ backend: "mpfree", "multi_chunk" or "2pac"
325
+ """
326
+ global pathes, input_path, output_path
327
+ if pathes[backend] is None:
328
+ _init_external_softwares(requires=[backend])
329
+
330
+
331
+ resolution_str = "--resolution" if full_resolution else ""
332
+ # print(mpfree_in_path + id, mpfree_out_path + id)
333
+ if id is None:
334
+ id = str(threading.get_native_id())
335
+ if not os.path.exists(path):
336
+ raise ValueError(f"No file found at {path}.")
337
+ if os.path.exists(output_path + id):
338
+ os.remove(output_path + id)
339
+ verbose_arg = "> /dev/null 2>&1" if not verbose else ""
340
+ if backend == "mpfree":
341
+ more_verbose = "-v" if verbose else ""
342
+ command = (
343
+ f"{pathes[backend]} {more_verbose} {resolution_str} --dim={dimension} {path} {output_path+id} {verbose_arg}"
344
+ )
345
+ elif backend == "multi_chunk":
346
+ command = (
347
+ f"{pathes[backend]} {path} {output_path+id} {verbose_arg}"
348
+ )
349
+ elif backend in ["twopac", "2pac"]:
350
+ command = (
351
+ f"{pathes[backend]} -f {path} --scc-input -n{dimension} --save-resolution-scc {output_path+id} {verbose_arg}"
352
+ )
353
+ else:
354
+ raise ValueError(f"Unsupported backend {backend}.")
355
+ if verbose:
356
+ print(f"Calling :\n\n {command}")
357
+ os.system(command)
358
+
359
+ slicer._build_from_scc_file(path=output_path+id, shift_dimension=shift_dimension)
360
+
361
+ if clear:
362
+ clear_io(input_path+id, output_path + id)
363
+
364
+
365
+ def reduce_complex(
366
+ complex, # Simplextree, Slicer, or str
367
+ bool full_resolution: bool = True,
368
+ int dimension: int | np.int64 = 1,
369
+ bool clear: bool = True,
370
+ id: Optional[str]=None, # For parallel stuff
371
+ bool verbose:bool=False,
372
+ backend:available_reduce_softs="mpfree"
373
+ ):
374
+ """
375
+ Computes a minimal presentation of the file in path,
376
+ using `backend`.
377
+
378
+ simplextree
379
+ full_resolution: bool
380
+ dimension: int, presentation dimension to consider
381
+ clear: bool, removes temporary files if True
382
+ id: str, temporary files are of this id, allowing for multiprocessing
383
+ verbose: bool
384
+ """
385
+
386
+ from multipers.simplex_tree_multi import is_simplextree_multi
387
+ if id is None:
388
+ id = str(threading.get_native_id())
389
+ path = input_path+id
390
+ if is_simplextree_multi(complex):
391
+ complex.to_scc(
392
+ path=path,
393
+ rivet_compatible=False,
394
+ strip_comments=False,
395
+ ignore_last_generators=False,
396
+ overwrite=True,
397
+ reverse_block=False,
398
+ )
399
+ dimension = complex.dimension - dimension
400
+ elif isinstance(complex,str):
401
+ path = complex
402
+ elif isinstance(complex, list) or isinstance(complex, tuple):
403
+ scc2disk(complex,path=path)
404
+ else:
405
+ # Assumes its a slicer
406
+ blocks = mps.slicer2blocks(complex)
407
+ scc2disk(blocks,path=path)
408
+ dimension = len(blocks) -2 -dimension
409
+
410
+ return scc_reduce_from_str(
411
+ path=path,
412
+ full_resolution=full_resolution,
413
+ dimension=dimension,
414
+ clear=clear,
415
+ id=id,
416
+ verbose=verbose,
417
+ backend=backend
418
+ )
419
+
420
+
421
+
422
+
423
+ def function_delaunay_presentation(
424
+ point_cloud:np.ndarray,
425
+ function_values:np.ndarray,
426
+ id:Optional[str] = None,
427
+ bool clear:bool = True,
428
+ bool verbose:bool=False,
429
+ int degree = -1,
430
+ bool multi_chunk = False,
431
+ ):
432
+ """
433
+ Computes a function delaunay presentation, and returns it as blocks.
434
+
435
+ points : (num_pts, n) float array
436
+ grades : (num_pts,) float array
437
+ degree (opt) : if given, computes a minimal presentation of this homological degree first
438
+ clear:bool, removes temporary files if true
439
+ degree: computes minimal presentation of this degree if given
440
+ verbose : bool
441
+ """
442
+ if id is None:
443
+ id = str(threading.get_native_id())
444
+ global input_path, output_path, pathes
445
+ backend = "function_delaunay"
446
+ if pathes[backend] is None :
447
+ _init_external_softwares(requires=[backend])
448
+
449
+ to_write = np.concatenate([point_cloud, function_values.reshape(-1,1)], axis=1)
450
+ np.savetxt(input_path+id,to_write,delimiter=' ')
451
+ verbose_arg = "> /dev/null 2>&1" if not verbose else ""
452
+ degree_arg = f"--minpres {degree}" if degree >= 0 else ""
453
+ multi_chunk_arg = "--multi-chunk" if multi_chunk else ""
454
+ if os.path.exists(output_path + id):
455
+ os.remove(output_path+ id)
456
+ command = f"{pathes[backend]} {degree_arg} {multi_chunk_arg} {input_path+id} {output_path+id} {verbose_arg} --no-delaunay-compare"
457
+ if verbose:
458
+ print(command)
459
+ os.system(command)
460
+
461
+ blocks = scc_parser(output_path + id)
462
+ if clear:
463
+ clear_io(output_path + id, input_path + id)
464
+ ## Function Delaunay workaround: last size is 0 but shouldn't...
465
+ if degree<0 and len(blocks) and not len(blocks[-1][1]):
466
+ blocks=blocks[:-1]
467
+
468
+ return blocks
469
+
470
+ def function_delaunay_presentation_to_slicer(
471
+ slicer,
472
+ point_cloud:np.ndarray,
473
+ function_values:np.ndarray,
474
+ id:Optional[str] = None,
475
+ bool clear:bool = True,
476
+ bool verbose:bool=False,
477
+ int degree = -1,
478
+ bool multi_chunk = False,
479
+ ):
480
+ """
481
+ Computes a function delaunay presentation, and returns it as a slicer.
482
+
483
+ slicer: empty slicer to fill
484
+ points : (num_pts, n) float array
485
+ grades : (num_pts,) float array
486
+ degree (opt) : if given, computes a minimal presentation of this homological degree first
487
+ clear:bool, removes temporary files if true
488
+ degree: computes minimal presentation of this degree if given
489
+ verbose : bool
490
+ """
491
+ if id is None:
492
+ id = str(threading.get_native_id())
493
+ global input_path, output_path, pathes
494
+ backend = "function_delaunay"
495
+ if pathes[backend] is None :
496
+ _init_external_softwares(requires=[backend])
497
+
498
+ to_write = np.concatenate([point_cloud, function_values.reshape(-1,1)], axis=1)
499
+ np.savetxt(input_path+id,to_write,delimiter=' ')
500
+ verbose_arg = "> /dev/null 2>&1" if not verbose else ""
501
+ degree_arg = f"--minpres {degree}" if degree >= 0 else ""
502
+ multi_chunk_arg = "--multi-chunk" if multi_chunk else ""
503
+ if os.path.exists(output_path + id):
504
+ os.remove(output_path+ id)
505
+ command = f"{pathes[backend]} {degree_arg} {multi_chunk_arg} {input_path+id} {output_path+id} {verbose_arg} --no-delaunay-compare"
506
+ if verbose:
507
+ print(command)
508
+ os.system(command)
509
+
510
+ slicer._build_from_scc_file(path=output_path+id, shift_dimension=-1 if degree <= 0 else degree-1 )
511
+
512
+ if clear:
513
+ clear_io(output_path + id, input_path + id)
514
+
515
+
516
+
517
+ def clear_io(*args):
518
+ """Removes temporary files"""
519
+ global input_path,output_path
520
+ for x in [input_path,output_path] + list(args):
521
+ if os.path.exists(x):
522
+ os.remove(x)
523
+
524
+
525
+
526
+
527
+
528
+
529
+ # cdef extern from "multiparameter_module_approximation/format_python-cpp.h" namespace "Gudhi::multiparameter::mma":
530
+ # pair[boundary_matrix, vector[One_critical_filtration[double]]] simplextree_to_boundary_filtration(intptr_t)
531
+ # vector[pair[ vector[vector[float]],boundary_matrix]] simplextree_to_scc(intptr_t)
532
+ # vector[pair[ vector[vector[vector[float]]],boundary_matrix]] function_simplextree_to_scc(intptr_t)
533
+ # pair[vector[vector[float]],boundary_matrix ] simplextree_to_ordered_bf(intptr_t)
534
+
535
+ # def simplex_tree2boundary_filtrations(simplextree:SimplexTreeMulti | SimplexTree):
536
+ # """Computes a (sparse) boundary matrix, with associated filtration. Can be used as an input of approx afterwards.
537
+ #
538
+ # Parameters
539
+ # ----------
540
+ # simplextree: Gudhi or mma simplextree
541
+ # The simplextree defining the filtration to convert to boundary-filtration.
542
+ #
543
+ # Returns
544
+ # -------
545
+ # B:List of lists of ints
546
+ # The boundary matrix.
547
+ # F: List of 1D filtration
548
+ # The filtrations aligned with B; the i-th simplex of this simplextree has boundary B[i] and filtration(s) F[i].
549
+ #
550
+ # """
551
+ # cdef intptr_t cptr
552
+ # if isinstance(simplextree, SimplexTreeMulti):
553
+ # cptr = simplextree.thisptr
554
+ # elif isinstance(simplextree, SimplexTree):
555
+ # temp_st = gd.SimplexTreeMulti(simplextree, parameters=1)
556
+ # cptr = temp_st.thisptr
557
+ # else:
558
+ # raise TypeError("Has to be a simplextree")
559
+ # cdef pair[boundary_matrix, vector[One_critical_filtration[double]]] cboundary_filtration = simplextree_to_boundary_filtration(cptr)
560
+ # boundary = cboundary_filtration.first
561
+ # # multi_filtrations = np.array(<vector[vector[float]]>One_critical_filtration.to_python(cboundary_filtration.second))
562
+ # cdef cnp.ndarray[double, ndim=2] multi_filtrations = _fmf2numpy_f64(cboundary_filtration.second)
563
+ # return boundary, multi_filtrations
564
+
565
+ # def simplextree2scc(simplextree:SimplexTreeMulti | SimplexTree, filtration_dtype=np.float32, bool flattened=False):
566
+ # """
567
+ # Turns a simplextree into a (simplicial) module presentation.
568
+ # """
569
+ # cdef intptr_t cptr
570
+ # cdef bool is_function_st = False
571
+ # if isinstance(simplextree, SimplexTreeMulti):
572
+ # cptr = simplextree.thisptr
573
+ # is_function_st = simplextree._is_function_simplextree
574
+ # elif isinstance(simplextree, SimplexTree):
575
+ # temp_st = gd.SimplexTreeMulti(simplextree, parameters=1)
576
+ # cptr = temp_st.thisptr
577
+ # else:
578
+ # raise TypeError("Has to be a simplextree")
579
+ #
580
+ # cdef pair[vector[vector[float]], boundary_matrix] out
581
+ # if flattened:
582
+ # out = simplextree_to_ordered_bf(cptr)
583
+ # return np.asarray(out.first,dtype=filtration_dtype), tuple(out.second)
584
+ #
585
+ # if is_function_st:
586
+ # blocks = function_simplextree_to_scc(cptr)
587
+ # else:
588
+ # blocks = simplextree_to_scc(cptr)
589
+ # # reduces the space in memory
590
+ # if is_function_st:
591
+ # blocks = [(tuple(f), tuple(b)) for f,b in blocks[::-1]]
592
+ # else:
593
+ # blocks = [(np.asarray(f,dtype=filtration_dtype), tuple(b)) for f,b in blocks[::-1]] ## presentation is on the other order
594
+ # return blocks+[(np.empty(0,dtype=filtration_dtype),[])]
595
+
596
+ @cython.boundscheck(False)
597
+ @cython.wraparound(False)
598
+ def scc2disk(
599
+ stuff,
600
+ path:str|os.PathLike,
601
+ int num_parameters = -1,
602
+ bool reverse_block = False,
603
+ bool rivet_compatible = False,
604
+ bool ignore_last_generators = False,
605
+ bool strip_comments = False,
606
+ ):
607
+ """
608
+ Writes a scc python format / blocks into a file.
609
+ """
610
+ if num_parameters == -1:
611
+ for block in stuff:
612
+ if len(block[0]) == 0:
613
+ continue
614
+ num_gens, num_parameters_= np.asarray(block[0]).shape
615
+ num_parameters = num_parameters_
616
+ break
617
+ assert num_parameters > 0, f"Invalid number of parameters {num_parameters}"
618
+
619
+ if reverse_block: stuff.reverse()
620
+ with open(path, "w") as f:
621
+ f.write("scc2020\n") if not rivet_compatible else f.write("firep\n")
622
+ if not strip_comments and not rivet_compatible: f.write("# Number of parameters\n")
623
+ if rivet_compatible:
624
+ assert num_parameters == 2
625
+ f.write("Filtration 1\n")
626
+ f.write("Filtration 2\n")
627
+ else:
628
+ f.write(f"{num_parameters}\n")
629
+
630
+ if not strip_comments: f.write("# Sizes of generating sets\n")
631
+ for block in stuff: f.write(f"{len(block[0])} ")
632
+ f.write("\n")
633
+ for i,block in enumerate(stuff):
634
+ if (rivet_compatible or ignore_last_generators) and i == len(stuff)-1: continue
635
+ if not strip_comments: f.write(f"# Block of dimension {len(stuff)-1-i}\n")
636
+ filtration, boundary = block
637
+ filtration = np.asarray(filtration).astype(str)
638
+ # boundary = tuple(x.astype(str) for x in boundary)
639
+ f.write(" ".join(itertools.chain.from_iterable(
640
+ ((*(f.tolist()), ";", *(np.asarray(b).astype(str).tolist()), "\n")
641
+ for f,b in zip(filtration, boundary))
642
+ )
643
+ ))
644
+ # for j in range(<int>len(filtration)):
645
+ # line = " ".join((
646
+ # *filtration[j],
647
+ # ";",
648
+ # *boundary[j],
649
+ # "\n",
650
+ # ))
651
+ # f.write(line)
652
+
653
+ def scc2disk_old(
654
+ stuff,
655
+ path:str|os.PathLike,
656
+ num_parameters = -1,
657
+ reverse_block = False,
658
+ rivet_compatible = False,
659
+ ignore_last_generators = False,
660
+ strip_comments = False,
661
+ ):
662
+ """
663
+ Writes a scc python format / blocks into a file.
664
+ """
665
+ if num_parameters == -1:
666
+ for block in stuff:
667
+ if len(block[0]) == 0:
668
+ continue
669
+ num_gens, num_parameters_= np.asarray(block[0]).shape
670
+ num_parameters = num_parameters_
671
+ break
672
+ assert num_parameters > 0, f"Invalid number of parameters {num_parameters}"
673
+
674
+ if reverse_block: stuff.reverse()
675
+ out = []
676
+ if rivet_compatible:
677
+ out.append(r"firep")
678
+ else:
679
+ out.append(r"scc2020")
680
+ if not strip_comments and not rivet_compatible:
681
+ out.append(r"# Number of parameters")
682
+ if rivet_compatible:
683
+ out.append("Filtration 1")
684
+ out.append("Filtration 2\n")
685
+ else:
686
+ out.append(f"{num_parameters}")
687
+
688
+ if not strip_comments:
689
+ out.append("# Sizes of generating sets")
690
+
691
+ # for block in stuff:
692
+ # f.write(f"{len(block[0])} ")
693
+ out.append(" ".join(str(len(block[0])) for block in stuff))
694
+ str_blocks = [out]
695
+ for i,block in enumerate(stuff):
696
+ if (rivet_compatible or ignore_last_generators) and i == len(stuff)-1: continue
697
+ if not strip_comments:
698
+ str_blocks.append([f"# Block of dimension {len(stuff)-1-i}"])
699
+ filtration, boundary = block
700
+ if len(filtration) == 0:
701
+ continue
702
+ filtration = filtration.astype(str)
703
+ C = filtration[:,0]
704
+ for i in range(1,filtration.shape[1]):
705
+ C = np.char.add(C," ")
706
+ C = np.char.add(C,filtration[:,i])
707
+ C = np.char.add(C, ";")
708
+ D = np.fromiter((" ".join(b.astype(str).tolist()) for b in boundary), dtype="<U11") #int32-> str is "<U11" #check np.array(1, dtype=np.int32).astype(str)
709
+ str_blocks.append(np.char.add(C,D))
710
+
711
+ np.savetxt("test.scc", np.concatenate(str_blocks), delimiter="", fmt="%s")