multipers 2.4.0b1__cp312-cp312-macosx_11_0_arm64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- multipers/.dylibs/libboost_timer.dylib +0 -0
- multipers/.dylibs/libc++.1.0.dylib +0 -0
- multipers/.dylibs/libtbb.12.17.dylib +0 -0
- multipers/__init__.py +33 -0
- multipers/_signed_measure_meta.py +426 -0
- multipers/_slicer_meta.py +231 -0
- multipers/array_api/__init__.py +62 -0
- multipers/array_api/numpy.py +124 -0
- multipers/array_api/torch.py +133 -0
- multipers/data/MOL2.py +458 -0
- multipers/data/UCR.py +18 -0
- multipers/data/__init__.py +1 -0
- multipers/data/graphs.py +466 -0
- multipers/data/immuno_regions.py +27 -0
- multipers/data/minimal_presentation_to_st_bf.py +0 -0
- multipers/data/pytorch2simplextree.py +91 -0
- multipers/data/shape3d.py +101 -0
- multipers/data/synthetic.py +113 -0
- multipers/distances.py +202 -0
- multipers/filtration_conversions.pxd +736 -0
- multipers/filtration_conversions.pxd.tp +226 -0
- multipers/filtrations/__init__.py +21 -0
- multipers/filtrations/density.py +529 -0
- multipers/filtrations/filtrations.py +480 -0
- multipers/filtrations.pxd +534 -0
- multipers/filtrations.pxd.tp +332 -0
- multipers/function_rips.cpython-312-darwin.so +0 -0
- multipers/function_rips.pyx +104 -0
- multipers/grids.cpython-312-darwin.so +0 -0
- multipers/grids.pyx +538 -0
- multipers/gudhi/Persistence_slices_interface.h +213 -0
- multipers/gudhi/Simplex_tree_interface.h +274 -0
- multipers/gudhi/Simplex_tree_multi_interface.h +648 -0
- multipers/gudhi/gudhi/Bitmap_cubical_complex.h +450 -0
- multipers/gudhi/gudhi/Bitmap_cubical_complex_base.h +1070 -0
- multipers/gudhi/gudhi/Bitmap_cubical_complex_periodic_boundary_conditions_base.h +579 -0
- multipers/gudhi/gudhi/Debug_utils.h +52 -0
- multipers/gudhi/gudhi/Degree_rips_bifiltration.h +2307 -0
- multipers/gudhi/gudhi/Dynamic_multi_parameter_filtration.h +2524 -0
- multipers/gudhi/gudhi/Fields/Multi_field.h +453 -0
- multipers/gudhi/gudhi/Fields/Multi_field_operators.h +460 -0
- multipers/gudhi/gudhi/Fields/Multi_field_shared.h +444 -0
- multipers/gudhi/gudhi/Fields/Multi_field_small.h +584 -0
- multipers/gudhi/gudhi/Fields/Multi_field_small_operators.h +490 -0
- multipers/gudhi/gudhi/Fields/Multi_field_small_shared.h +580 -0
- multipers/gudhi/gudhi/Fields/Z2_field.h +391 -0
- multipers/gudhi/gudhi/Fields/Z2_field_operators.h +389 -0
- multipers/gudhi/gudhi/Fields/Zp_field.h +493 -0
- multipers/gudhi/gudhi/Fields/Zp_field_operators.h +384 -0
- multipers/gudhi/gudhi/Fields/Zp_field_shared.h +492 -0
- multipers/gudhi/gudhi/Flag_complex_edge_collapser.h +337 -0
- multipers/gudhi/gudhi/Matrix.h +2200 -0
- multipers/gudhi/gudhi/Multi_filtration/Multi_parameter_generator.h +1712 -0
- multipers/gudhi/gudhi/Multi_filtration/multi_filtration_conversions.h +237 -0
- multipers/gudhi/gudhi/Multi_filtration/multi_filtration_utils.h +225 -0
- multipers/gudhi/gudhi/Multi_parameter_filtered_complex.h +485 -0
- multipers/gudhi/gudhi/Multi_parameter_filtration.h +2643 -0
- multipers/gudhi/gudhi/Multi_persistence/Box.h +233 -0
- multipers/gudhi/gudhi/Multi_persistence/Line.h +309 -0
- multipers/gudhi/gudhi/Multi_persistence/Multi_parameter_filtered_complex_pcoh_interface.h +268 -0
- multipers/gudhi/gudhi/Multi_persistence/Persistence_interface_cohomology.h +159 -0
- multipers/gudhi/gudhi/Multi_persistence/Persistence_interface_matrix.h +463 -0
- multipers/gudhi/gudhi/Multi_persistence/Point.h +853 -0
- multipers/gudhi/gudhi/Off_reader.h +173 -0
- multipers/gudhi/gudhi/Persistence_matrix/Base_matrix.h +834 -0
- multipers/gudhi/gudhi/Persistence_matrix/Base_matrix_with_column_compression.h +838 -0
- multipers/gudhi/gudhi/Persistence_matrix/Boundary_matrix.h +833 -0
- multipers/gudhi/gudhi/Persistence_matrix/Chain_matrix.h +1367 -0
- multipers/gudhi/gudhi/Persistence_matrix/Id_to_index_overlay.h +1157 -0
- multipers/gudhi/gudhi/Persistence_matrix/Position_to_index_overlay.h +869 -0
- multipers/gudhi/gudhi/Persistence_matrix/RU_matrix.h +905 -0
- multipers/gudhi/gudhi/Persistence_matrix/allocators/entry_constructors.h +122 -0
- multipers/gudhi/gudhi/Persistence_matrix/base_pairing.h +260 -0
- multipers/gudhi/gudhi/Persistence_matrix/base_swap.h +288 -0
- multipers/gudhi/gudhi/Persistence_matrix/chain_pairing.h +170 -0
- multipers/gudhi/gudhi/Persistence_matrix/chain_rep_cycles.h +247 -0
- multipers/gudhi/gudhi/Persistence_matrix/chain_vine_swap.h +571 -0
- multipers/gudhi/gudhi/Persistence_matrix/columns/chain_column_extra_properties.h +182 -0
- multipers/gudhi/gudhi/Persistence_matrix/columns/column_dimension_holder.h +130 -0
- multipers/gudhi/gudhi/Persistence_matrix/columns/column_utilities.h +235 -0
- multipers/gudhi/gudhi/Persistence_matrix/columns/entry_types.h +312 -0
- multipers/gudhi/gudhi/Persistence_matrix/columns/heap_column.h +1092 -0
- multipers/gudhi/gudhi/Persistence_matrix/columns/intrusive_list_column.h +923 -0
- multipers/gudhi/gudhi/Persistence_matrix/columns/intrusive_set_column.h +914 -0
- multipers/gudhi/gudhi/Persistence_matrix/columns/list_column.h +930 -0
- multipers/gudhi/gudhi/Persistence_matrix/columns/naive_vector_column.h +1071 -0
- multipers/gudhi/gudhi/Persistence_matrix/columns/row_access.h +203 -0
- multipers/gudhi/gudhi/Persistence_matrix/columns/set_column.h +886 -0
- multipers/gudhi/gudhi/Persistence_matrix/columns/unordered_set_column.h +984 -0
- multipers/gudhi/gudhi/Persistence_matrix/columns/vector_column.h +1213 -0
- multipers/gudhi/gudhi/Persistence_matrix/index_mapper.h +58 -0
- multipers/gudhi/gudhi/Persistence_matrix/matrix_dimension_holders.h +227 -0
- multipers/gudhi/gudhi/Persistence_matrix/matrix_row_access.h +200 -0
- multipers/gudhi/gudhi/Persistence_matrix/ru_pairing.h +166 -0
- multipers/gudhi/gudhi/Persistence_matrix/ru_rep_cycles.h +319 -0
- multipers/gudhi/gudhi/Persistence_matrix/ru_vine_swap.h +562 -0
- multipers/gudhi/gudhi/Persistence_on_a_line.h +152 -0
- multipers/gudhi/gudhi/Persistence_on_rectangle.h +617 -0
- multipers/gudhi/gudhi/Persistent_cohomology/Field_Zp.h +118 -0
- multipers/gudhi/gudhi/Persistent_cohomology/Multi_field.h +173 -0
- multipers/gudhi/gudhi/Persistent_cohomology/Persistent_cohomology_column.h +128 -0
- multipers/gudhi/gudhi/Persistent_cohomology.h +769 -0
- multipers/gudhi/gudhi/Points_off_io.h +171 -0
- multipers/gudhi/gudhi/Projective_cover_kernel.h +379 -0
- multipers/gudhi/gudhi/Simple_object_pool.h +69 -0
- multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_iterators.h +559 -0
- multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_node_explicit_storage.h +83 -0
- multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_siblings.h +121 -0
- multipers/gudhi/gudhi/Simplex_tree/Simplex_tree_star_simplex_iterators.h +277 -0
- multipers/gudhi/gudhi/Simplex_tree/filtration_value_utils.h +155 -0
- multipers/gudhi/gudhi/Simplex_tree/hooks_simplex_base.h +62 -0
- multipers/gudhi/gudhi/Simplex_tree/indexing_tag.h +27 -0
- multipers/gudhi/gudhi/Simplex_tree/serialization_utils.h +60 -0
- multipers/gudhi/gudhi/Simplex_tree/simplex_tree_options.h +105 -0
- multipers/gudhi/gudhi/Simplex_tree.h +3170 -0
- multipers/gudhi/gudhi/Slicer.h +848 -0
- multipers/gudhi/gudhi/Thread_safe_slicer.h +393 -0
- multipers/gudhi/gudhi/distance_functions.h +62 -0
- multipers/gudhi/gudhi/graph_simplicial_complex.h +104 -0
- multipers/gudhi/gudhi/multi_simplex_tree_helpers.h +147 -0
- multipers/gudhi/gudhi/persistence_interval.h +263 -0
- multipers/gudhi/gudhi/persistence_matrix_options.h +188 -0
- multipers/gudhi/gudhi/reader_utils.h +367 -0
- multipers/gudhi/gudhi/simple_mdspan.h +484 -0
- multipers/gudhi/gudhi/slicer_helpers.h +779 -0
- multipers/gudhi/tmp_h0_pers/mma_interface_h0.h +223 -0
- multipers/gudhi/tmp_h0_pers/naive_merge_tree.h +536 -0
- multipers/io.cpython-312-darwin.so +0 -0
- multipers/io.pyx +472 -0
- multipers/ml/__init__.py +0 -0
- multipers/ml/accuracies.py +90 -0
- multipers/ml/invariants_with_persistable.py +79 -0
- multipers/ml/kernels.py +176 -0
- multipers/ml/mma.py +713 -0
- multipers/ml/one.py +472 -0
- multipers/ml/point_clouds.py +352 -0
- multipers/ml/signed_measures.py +1667 -0
- multipers/ml/sliced_wasserstein.py +461 -0
- multipers/ml/tools.py +113 -0
- multipers/mma_structures.cpython-312-darwin.so +0 -0
- multipers/mma_structures.pxd +134 -0
- multipers/mma_structures.pyx +1483 -0
- multipers/mma_structures.pyx.tp +1126 -0
- multipers/multi_parameter_rank_invariant/diff_helpers.h +85 -0
- multipers/multi_parameter_rank_invariant/euler_characteristic.h +95 -0
- multipers/multi_parameter_rank_invariant/function_rips.h +317 -0
- multipers/multi_parameter_rank_invariant/hilbert_function.h +761 -0
- multipers/multi_parameter_rank_invariant/persistence_slices.h +149 -0
- multipers/multi_parameter_rank_invariant/rank_invariant.h +350 -0
- multipers/multiparameter_edge_collapse.py +41 -0
- multipers/multiparameter_module_approximation/approximation.h +2541 -0
- multipers/multiparameter_module_approximation/debug.h +107 -0
- multipers/multiparameter_module_approximation/format_python-cpp.h +292 -0
- multipers/multiparameter_module_approximation/utilities.h +428 -0
- multipers/multiparameter_module_approximation.cpython-312-darwin.so +0 -0
- multipers/multiparameter_module_approximation.pyx +286 -0
- multipers/ops.cpython-312-darwin.so +0 -0
- multipers/ops.pyx +231 -0
- multipers/pickle.py +89 -0
- multipers/plots.py +550 -0
- multipers/point_measure.cpython-312-darwin.so +0 -0
- multipers/point_measure.pyx +409 -0
- multipers/simplex_tree_multi.cpython-312-darwin.so +0 -0
- multipers/simplex_tree_multi.pxd +136 -0
- multipers/simplex_tree_multi.pyx +11719 -0
- multipers/simplex_tree_multi.pyx.tp +2102 -0
- multipers/slicer.cpython-312-darwin.so +0 -0
- multipers/slicer.pxd +2097 -0
- multipers/slicer.pxd.tp +263 -0
- multipers/slicer.pyx +13042 -0
- multipers/slicer.pyx.tp +1259 -0
- multipers/tensor/tensor.h +672 -0
- multipers/tensor.pxd +13 -0
- multipers/test.pyx +44 -0
- multipers/tests/__init__.py +70 -0
- multipers/torch/__init__.py +1 -0
- multipers/torch/diff_grids.py +240 -0
- multipers/torch/rips_density.py +310 -0
- multipers/vector_interface.pxd +46 -0
- multipers-2.4.0b1.dist-info/METADATA +131 -0
- multipers-2.4.0b1.dist-info/RECORD +184 -0
- multipers-2.4.0b1.dist-info/WHEEL +6 -0
- multipers-2.4.0b1.dist-info/licenses/LICENSE +21 -0
- multipers-2.4.0b1.dist-info/top_level.txt +1 -0
multipers/grids.pyx
ADDED
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
|
|
2
|
+
from libc.stdint cimport intptr_t, int32_t, int64_t
|
|
3
|
+
from libcpp cimport bool,int, float
|
|
4
|
+
|
|
5
|
+
cimport numpy as cnp
|
|
6
|
+
import numpy as np
|
|
7
|
+
cnp.import_array()
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
from typing import Iterable,Literal,Optional
|
|
11
|
+
from itertools import product
|
|
12
|
+
from multipers.array_api import api_from_tensor, api_from_tensors
|
|
13
|
+
from multipers.array_api import numpy as npapi
|
|
14
|
+
from multipers.array_api import check_keops
|
|
15
|
+
|
|
16
|
+
available_strategies = ["regular","regular_closest", "regular_left", "partition", "quantile", "precomputed"]
|
|
17
|
+
Lstrategies = Literal["regular","regular_closest", "regular_left", "partition", "quantile", "precomputed"]
|
|
18
|
+
|
|
19
|
+
ctypedef fused some_int:
|
|
20
|
+
int32_t
|
|
21
|
+
int64_t
|
|
22
|
+
|
|
23
|
+
ctypedef fused some_float:
|
|
24
|
+
float
|
|
25
|
+
double
|
|
26
|
+
|
|
27
|
+
def sanitize_grid(grid, bool numpyfy=False, bool add_inf=False):
|
|
28
|
+
cdef int num_parameters = len(grid)
|
|
29
|
+
if num_parameters == 0:
|
|
30
|
+
raise ValueError("empty filtration grid")
|
|
31
|
+
api = api_from_tensors(*grid)
|
|
32
|
+
if numpyfy:
|
|
33
|
+
grid = tuple(api.asnumpy(grid[i]) for i in range(num_parameters))
|
|
34
|
+
else:
|
|
35
|
+
# copy here may not be necessary, but cheap
|
|
36
|
+
grid = tuple(api.astensor(grid[i]) for i in range(num_parameters))
|
|
37
|
+
if add_inf:
|
|
38
|
+
api = api_from_tensors(grid[0])
|
|
39
|
+
inf = api.astensor(_inf_value(grid[0]))
|
|
40
|
+
grid = tuple(
|
|
41
|
+
grid[i] if grid[i][-1] == inf
|
|
42
|
+
else api.cat([grid[i], inf[None]])
|
|
43
|
+
for i in range(num_parameters)
|
|
44
|
+
)
|
|
45
|
+
assert np.all([g.ndim==1 for g in grid])
|
|
46
|
+
return grid
|
|
47
|
+
|
|
48
|
+
def threshold_slice(a, m,M):
|
|
49
|
+
if m is not None:
|
|
50
|
+
a = a[a>=m]
|
|
51
|
+
if M is not None:
|
|
52
|
+
a = a[a<=M]
|
|
53
|
+
return a
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def compute_grid(
|
|
59
|
+
x,
|
|
60
|
+
resolution:Optional[int|Iterable[int]]=None,
|
|
61
|
+
strategy:Lstrategies="exact",
|
|
62
|
+
bool unique=True,
|
|
63
|
+
some_float _q_factor=1.,
|
|
64
|
+
drop_quantiles=[0,0],
|
|
65
|
+
bool dense = False,
|
|
66
|
+
threshold_min = None,
|
|
67
|
+
threshold_max = None,
|
|
68
|
+
):
|
|
69
|
+
"""
|
|
70
|
+
Computes a grid from filtration values, using some strategy.
|
|
71
|
+
|
|
72
|
+
Input
|
|
73
|
+
-----
|
|
74
|
+
|
|
75
|
+
- `filtrations_values`: `Iterable[filtration of parameter for parameter]`
|
|
76
|
+
where `filtration_of_parameter` is a array[float, ndim=1]
|
|
77
|
+
- `resolution`:Optional[int|tuple[int]]
|
|
78
|
+
- `strategy`: either exact, regular, regular_closest, regular_left, partition, quantile, or precomputed.
|
|
79
|
+
- `unique`: if true, doesn't repeat values in the output grid.
|
|
80
|
+
- `drop_quantiles` : drop some filtration values according to these quantiles
|
|
81
|
+
Output
|
|
82
|
+
------
|
|
83
|
+
|
|
84
|
+
Iterable[array[float, ndim=1]] : the 1d-grid for each parameter.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
from multipers.slicer import is_slicer
|
|
88
|
+
from multipers.simplex_tree_multi import is_simplextree_multi
|
|
89
|
+
from multipers.mma_structures import is_mma
|
|
90
|
+
|
|
91
|
+
if resolution is not None and strategy == "exact":
|
|
92
|
+
raise ValueError("The 'exact' strategy does not support resolution.")
|
|
93
|
+
if strategy != "exact":
|
|
94
|
+
assert resolution is not None, "A resolution is required for non-exact strategies"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
cdef bool is_numpy_compatible = True
|
|
98
|
+
if (is_slicer(x) or is_simplextree_multi(x)) and x.is_squeezed:
|
|
99
|
+
initial_grid = x.filtration_grid
|
|
100
|
+
api = api_from_tensors(*initial_grid)
|
|
101
|
+
elif is_slicer(x):
|
|
102
|
+
initial_grid = x.get_filtrations_values().T
|
|
103
|
+
api = npapi
|
|
104
|
+
elif is_simplextree_multi(x):
|
|
105
|
+
initial_grid = x.get_filtration_grid()
|
|
106
|
+
api = npapi
|
|
107
|
+
elif is_mma(x):
|
|
108
|
+
initial_grid = x.get_filtration_values()
|
|
109
|
+
api = npapi
|
|
110
|
+
elif isinstance(x, np.ndarray):
|
|
111
|
+
initial_grid = x
|
|
112
|
+
api = npapi
|
|
113
|
+
else:
|
|
114
|
+
x = tuple(x)
|
|
115
|
+
if len(x) == 0: return []
|
|
116
|
+
first = x[0]
|
|
117
|
+
## is_sm, i.e., iterable tuple(pts,weights)
|
|
118
|
+
if isinstance(first, tuple) and getattr(first[0], "shape", None) is not None:
|
|
119
|
+
initial_grid = tuple(f[0].T for f in x)
|
|
120
|
+
api = api_from_tensors(*initial_grid)
|
|
121
|
+
initial_grid = api.cat(initial_grid, axis=1)
|
|
122
|
+
## is grid-like (num_params, num_pts)
|
|
123
|
+
else:
|
|
124
|
+
api = api_from_tensors(*x)
|
|
125
|
+
initial_grid = tuple(api.astensor(f) for f in x)
|
|
126
|
+
|
|
127
|
+
cdef int num_parameters = len(initial_grid)
|
|
128
|
+
try:
|
|
129
|
+
int(resolution)
|
|
130
|
+
resolution = [resolution]*num_parameters
|
|
131
|
+
except TypeError:
|
|
132
|
+
pass
|
|
133
|
+
|
|
134
|
+
if threshold_min is not None or threshold_max is not None:
|
|
135
|
+
if threshold_min is None:
|
|
136
|
+
threshold_min = [None]*num_parameters
|
|
137
|
+
if threshold_max is None:
|
|
138
|
+
threshold_max = [None]*num_parameters
|
|
139
|
+
|
|
140
|
+
initial_grid = [
|
|
141
|
+
threshold_slice(x,a,b)
|
|
142
|
+
for x,a,b in zip(initial_grid, threshold_min, threshold_max)
|
|
143
|
+
]
|
|
144
|
+
|
|
145
|
+
grid = _compute_grid_numpy(
|
|
146
|
+
initial_grid,
|
|
147
|
+
resolution=resolution,
|
|
148
|
+
strategy = strategy,
|
|
149
|
+
unique = unique,
|
|
150
|
+
_q_factor=_q_factor,
|
|
151
|
+
drop_quantiles=drop_quantiles,
|
|
152
|
+
dense = dense,
|
|
153
|
+
)
|
|
154
|
+
# from multipers.torch.diff_grids import get_grid
|
|
155
|
+
# grid = get_grid(strategy)(initial_grid,resolution)
|
|
156
|
+
if dense:
|
|
157
|
+
grid = todense(grid)
|
|
158
|
+
return grid
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _compute_grid_numpy(
|
|
165
|
+
filtrations_values,
|
|
166
|
+
resolution=None,
|
|
167
|
+
strategy:Lstrategies="exact",
|
|
168
|
+
bool unique=True,
|
|
169
|
+
some_float _q_factor=1.,
|
|
170
|
+
drop_quantiles=[0,0],
|
|
171
|
+
bool dense = False,
|
|
172
|
+
):
|
|
173
|
+
"""
|
|
174
|
+
Computes a grid from filtration values, using some strategy.
|
|
175
|
+
|
|
176
|
+
Input
|
|
177
|
+
-----
|
|
178
|
+
- `filtrations_values`: `Iterable[filtration of parameter for parameter]`
|
|
179
|
+
where `filtration_of_parameter` is a array[float, ndim=1]
|
|
180
|
+
- `resolution`:Optional[int|tuple[int]]
|
|
181
|
+
- `strategy`: either exact, regular, regular_closest, regular_left, partition, quantile, or precomputed.
|
|
182
|
+
- `unique`: if true, doesn't repeat values in the output grid.
|
|
183
|
+
- `drop_quantiles` : drop some filtration values according to these quantiles
|
|
184
|
+
Output
|
|
185
|
+
------
|
|
186
|
+
Iterable[array[float, ndim=1]] : the 1d-grid for each parameter.
|
|
187
|
+
"""
|
|
188
|
+
num_parameters = len(filtrations_values)
|
|
189
|
+
api = api_from_tensors(*filtrations_values)
|
|
190
|
+
try:
|
|
191
|
+
a,b=drop_quantiles
|
|
192
|
+
except:
|
|
193
|
+
a,b=drop_quantiles,drop_quantiles
|
|
194
|
+
|
|
195
|
+
if a != 0 or b != 0:
|
|
196
|
+
boxes = api.astensor([api.quantile_closest(filtration, [a, b], axis=1) for filtration in filtrations_values])
|
|
197
|
+
min_filtration, max_filtration = api.minvalues(boxes, axis=(0,1)), api.maxvalues(boxes, axis=(0,1)) # box, birth/death, filtration
|
|
198
|
+
filtrations_values = [
|
|
199
|
+
filtration[(m<filtration) * (filtration <M)]
|
|
200
|
+
for filtration, m,M in zip(filtrations_values, min_filtration, max_filtration)
|
|
201
|
+
]
|
|
202
|
+
|
|
203
|
+
## match doesn't work with cython BUG
|
|
204
|
+
if strategy == "exact":
|
|
205
|
+
F=tuple(api.unique(f) for f in filtrations_values)
|
|
206
|
+
elif strategy == "quantile":
|
|
207
|
+
F = tuple(api.unique(f) for f in filtrations_values)
|
|
208
|
+
max_resolution = [min(len(f),r) for f,r in zip(F,resolution)]
|
|
209
|
+
F = tuple( api.quantile_closest(f, q=api.linspace(0,1,int(r*_q_factor)), axis=0) for f,r in zip(F, resolution) )
|
|
210
|
+
if unique:
|
|
211
|
+
F = tuple(api.unique(f) for f in F)
|
|
212
|
+
if np.all(np.asarray(max_resolution) > np.asarray([len(f) for f in F])):
|
|
213
|
+
return _compute_grid_numpy(filtrations_values=filtrations_values, resolution=resolution, strategy="quantile",_q_factor=1.5*_q_factor)
|
|
214
|
+
elif strategy == "regular":
|
|
215
|
+
F = tuple(_todo_regular(f,r,api) for f,r in zip(filtrations_values, resolution))
|
|
216
|
+
elif strategy == "regular_closest":
|
|
217
|
+
F = tuple(_todo_regular_closest(f,r, unique,api) for f,r in zip(filtrations_values, resolution))
|
|
218
|
+
elif strategy == "regular_left":
|
|
219
|
+
F = tuple(_todo_regular_left(f,r, unique,api) for f,r in zip(filtrations_values, resolution))
|
|
220
|
+
# elif strategy == "torch_regular_closest":
|
|
221
|
+
# F = tuple(_torch_regular_closest(f,r, unique) for f,r in zip(filtrations_values, resolution))
|
|
222
|
+
elif strategy == "partition":
|
|
223
|
+
F = tuple(_todo_partition(f,r, unique, api) for f,r in zip(filtrations_values, resolution))
|
|
224
|
+
elif strategy == "precomputed":
|
|
225
|
+
F=filtrations_values
|
|
226
|
+
else:
|
|
227
|
+
raise ValueError(f"Invalid strategy {strategy}. Pick something in {available_strategies}.")
|
|
228
|
+
if dense:
|
|
229
|
+
return todense(F)
|
|
230
|
+
return F
|
|
231
|
+
|
|
232
|
+
def todense(grid, bool product_order=False):
|
|
233
|
+
if len(grid) == 0:
|
|
234
|
+
return np.empty(0)
|
|
235
|
+
api = api_from_tensors(*grid)
|
|
236
|
+
# if product_order:
|
|
237
|
+
# if not api.backend ==np:
|
|
238
|
+
# raise NotImplementedError("only numpy here.")
|
|
239
|
+
# return np.fromiter(product(*grid), dtype=np.dtype((dtype, len(grid))), count=np.prod([len(f) for f in grid]))
|
|
240
|
+
return api.cartesian_product(*grid)
|
|
241
|
+
# if not isinstance(grid[0], np.ndarray):
|
|
242
|
+
# import torch
|
|
243
|
+
# assert isinstance(grid[0], torch.Tensor)
|
|
244
|
+
# from multipers.torch.diff_grids import todense
|
|
245
|
+
# return todense(grid)
|
|
246
|
+
# dtype = grid[0].dtype
|
|
247
|
+
# if product_order:
|
|
248
|
+
# return np.fromiter(product(*grid), dtype=np.dtype((dtype, len(grid))), count=np.prod([len(f) for f in grid]))
|
|
249
|
+
# mesh = np.meshgrid(*grid)
|
|
250
|
+
# coordinates = np.stack(mesh, axis=-1).reshape(-1, len(grid)).astype(dtype)
|
|
251
|
+
# return coordinates
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _todo_regular(f, int r, api):
|
|
256
|
+
if api.has_grad(f):
|
|
257
|
+
from warnings import warn
|
|
258
|
+
warn("`strategy=regular` is not differentiable. Removing grad.")
|
|
259
|
+
with api.no_grad():
|
|
260
|
+
return api.linspace(api.min(f), api.max(f), r)
|
|
261
|
+
|
|
262
|
+
def _project_on_1d_grid(f,grid, bool unique, api):
|
|
263
|
+
# api=api_from_tensors(f,grid)
|
|
264
|
+
if f.ndim != 1:
|
|
265
|
+
raise ValueError(f"Got ndim!=1. {f=}")
|
|
266
|
+
f = api.unique(f)
|
|
267
|
+
with api.no_grad():
|
|
268
|
+
_f = api.LazyTensor(f[:, None, None])
|
|
269
|
+
_f_reg = api.LazyTensor(grid[None, :, None])
|
|
270
|
+
indices = (_f - _f_reg).abs().argmin(0).ravel()
|
|
271
|
+
f = api.cat([f, api.tensor([api.inf], dtype=f.dtype)])
|
|
272
|
+
f_proj = f[indices]
|
|
273
|
+
if unique:
|
|
274
|
+
f_proj = api.unique(f_proj)
|
|
275
|
+
return f_proj
|
|
276
|
+
|
|
277
|
+
def _todo_regular_closest_keops(f, int r, bool unique, api):
|
|
278
|
+
f = api.astensor(f)
|
|
279
|
+
with api.no_grad():
|
|
280
|
+
f_regular = api.linspace(api.min(f), api.max(f), r, device = api.device(f),dtype=f.dtype)
|
|
281
|
+
return _project_on_1d_grid(f,f_regular,unique,api)
|
|
282
|
+
|
|
283
|
+
def _todo_regular_closest_old(some_float[:] f, int r, bool unique, api=None):
|
|
284
|
+
f_array = np.asarray(f)
|
|
285
|
+
f_regular = np.linspace(np.min(f), np.max(f),num=r, dtype=f_array.dtype)
|
|
286
|
+
f_regular_closest = np.asarray([f[<int64_t>np.argmin(np.abs(f_array-f_regular[i]))] for i in range(r)], dtype=f_array.dtype)
|
|
287
|
+
if unique: f_regular_closest = np.unique(f_regular_closest)
|
|
288
|
+
return f_regular_closest
|
|
289
|
+
|
|
290
|
+
def _todo_regular_left(f, int r, bool unique,api):
|
|
291
|
+
sorted_f = api.sort(f)
|
|
292
|
+
with api.no_grad():
|
|
293
|
+
f_regular = api.linspace(sorted_f[0],sorted_f[-1],r, dtype=sorted_f.dtype, device=api.device(sorted_f))
|
|
294
|
+
idx=api.searchsorted(sorted_f,f_regular)
|
|
295
|
+
f_regular_closest = sorted_f[idx]
|
|
296
|
+
if unique: f_regular_closest = api.unique(f_regular_closest)
|
|
297
|
+
return f_regular_closest
|
|
298
|
+
|
|
299
|
+
def _todo_regular_left_old(some_float[:] f, int r, bool unique):
|
|
300
|
+
sorted_f = np.sort(f)
|
|
301
|
+
f_regular = np.linspace(sorted_f[0],sorted_f[-1],num=r, dtype=sorted_f.dtype)
|
|
302
|
+
f_regular_closest = sorted_f[np.searchsorted(sorted_f,f_regular)]
|
|
303
|
+
if unique: f_regular_closest = np.unique(f_regular_closest)
|
|
304
|
+
return f_regular_closest
|
|
305
|
+
|
|
306
|
+
def _todo_partition(x, int resolution, bool unique, api):
|
|
307
|
+
if api.has_grad(x):
|
|
308
|
+
from warnings import warn
|
|
309
|
+
warn("`strategy=partition` is not differentiable. Removing grad.")
|
|
310
|
+
out = _todo_partition_(api.asnumpy(x), resolution, unique)
|
|
311
|
+
return api.from_numpy(out)
|
|
312
|
+
|
|
313
|
+
def _todo_partition_(some_float[:] data,int resolution, bool unique):
|
|
314
|
+
if data.shape[0] < resolution: resolution=data.shape[0]
|
|
315
|
+
k = data.shape[0] // resolution
|
|
316
|
+
partitions = np.partition(data, k)
|
|
317
|
+
f = partitions[[i*k for i in range(resolution)]]
|
|
318
|
+
if unique: f= np.unique(f)
|
|
319
|
+
return f
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
if check_keops():
|
|
323
|
+
_todo_regular_closest = _todo_regular_closest_keops
|
|
324
|
+
else:
|
|
325
|
+
_todo_regular_closest = _todo_regular_closest_old
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def compute_bounding_box(stuff, inflate = 0.):
|
|
329
|
+
r"""
|
|
330
|
+
Returns a array of shape (2, num_parameters)
|
|
331
|
+
such that for any filtration value $y$ of something in stuff,
|
|
332
|
+
then if (x,z) is the output of this function, we have
|
|
333
|
+
$x\le y \le z$.
|
|
334
|
+
"""
|
|
335
|
+
box = np.array(compute_grid(stuff,strategy="regular",resolution=2)).T
|
|
336
|
+
if inflate:
|
|
337
|
+
box[0] -= inflate
|
|
338
|
+
box[1] += inflate
|
|
339
|
+
return box
|
|
340
|
+
|
|
341
|
+
def push_to_grid(some_float[:,:] points, grid, bool return_coordinate=False):
|
|
342
|
+
"""
|
|
343
|
+
Given points and a grid (list of one parameter grids),
|
|
344
|
+
pushes the points onto the grid.
|
|
345
|
+
"""
|
|
346
|
+
num_points, num_parameters = points.shape[0], points.shape[1]
|
|
347
|
+
cdef cnp.ndarray[int64_t,ndim=2] coordinates = np.empty((num_points, num_parameters),dtype=np.int64)
|
|
348
|
+
for parameter in range(num_parameters):
|
|
349
|
+
coordinates[:,parameter] = np.searchsorted(grid[parameter],points[:,parameter])
|
|
350
|
+
if return_coordinate:
|
|
351
|
+
return coordinates
|
|
352
|
+
out = np.empty((num_points,num_parameters), grid[0].dtype)
|
|
353
|
+
for parameter in range(num_parameters):
|
|
354
|
+
out[:,parameter] = grid[parameter][coordinates[:,parameter]]
|
|
355
|
+
return out
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def coarsen_points(some_float[:,:] points, strategy="exact", int resolution=-1, bool coordinate=False):
|
|
359
|
+
grid = _compute_grid_numpy(points.T, strategy=strategy, resolution=resolution)
|
|
360
|
+
if coordinate:
|
|
361
|
+
return push_to_grid(points, grid, coordinate), grid
|
|
362
|
+
return push_to_grid(points, grid, coordinate)
|
|
363
|
+
|
|
364
|
+
def _inf_value(array):
|
|
365
|
+
if isinstance(array, type|np.dtype):
|
|
366
|
+
dtype = np.dtype(array) # torch types are not types
|
|
367
|
+
elif isinstance(array, np.ndarray):
|
|
368
|
+
dtype = np.dtype(array.dtype)
|
|
369
|
+
else:
|
|
370
|
+
import torch
|
|
371
|
+
if isinstance(array, torch.Tensor):
|
|
372
|
+
dtype=array.dtype
|
|
373
|
+
elif isinstance(array, torch.dtype):
|
|
374
|
+
dtype=array
|
|
375
|
+
else:
|
|
376
|
+
raise ValueError(f"unknown input of type {type(array)=} {array=}")
|
|
377
|
+
|
|
378
|
+
if isinstance(dtype, np.dtype):
|
|
379
|
+
if dtype.kind == 'f':
|
|
380
|
+
return np.asarray(np.inf,dtype=dtype)
|
|
381
|
+
if dtype.kind == 'i':
|
|
382
|
+
return np.iinfo(dtype).max
|
|
383
|
+
# torch only here.
|
|
384
|
+
if dtype.is_floating_point:
|
|
385
|
+
return torch.tensor(torch.inf, dtype=dtype)
|
|
386
|
+
else:
|
|
387
|
+
return torch.iinfo(dtype).max
|
|
388
|
+
raise ValueError(f"Dtype must be integer or floating like (got {dtype})")
|
|
389
|
+
|
|
390
|
+
def evaluate_in_grid(pts, grid, mass_default=None, input_inf_value=None, output_inf_value=None):
|
|
391
|
+
"""
|
|
392
|
+
Input
|
|
393
|
+
-----
|
|
394
|
+
- pts: of the form array[int, ndim=2]
|
|
395
|
+
- grid of the form Iterable[array[float, ndim=1]]
|
|
396
|
+
"""
|
|
397
|
+
assert pts.ndim == 2
|
|
398
|
+
first_filtration = grid[0]
|
|
399
|
+
dtype = first_filtration.dtype
|
|
400
|
+
api = api_from_tensors(*grid)
|
|
401
|
+
if mass_default is not None:
|
|
402
|
+
grid = tuple(api.cat([g, api.astensor(m)[None]]) for g,m in zip(grid, mass_default))
|
|
403
|
+
def empty_like(x):
|
|
404
|
+
return api.empty(x.shape, dtype=dtype)
|
|
405
|
+
|
|
406
|
+
coords=empty_like(pts)
|
|
407
|
+
cdef int dim = coords.shape[1]
|
|
408
|
+
pts_inf = _inf_value(pts) if input_inf_value is None else input_inf_value
|
|
409
|
+
coords_inf = _inf_value(coords) if output_inf_value is None else output_inf_value
|
|
410
|
+
idx = np.argwhere(pts == pts_inf)
|
|
411
|
+
pts[idx[:,0],idx[:,1]] = 0
|
|
412
|
+
for i in range(dim):
|
|
413
|
+
coords[:,i] = grid[i][pts[:,i]]
|
|
414
|
+
coords[idx[:,0],idx[:,1]] = coords_inf
|
|
415
|
+
return coords
|
|
416
|
+
|
|
417
|
+
def sm_in_grid(pts, weights, grid, mass_default=None):
|
|
418
|
+
"""Given a measure whose points are coordinates,
|
|
419
|
+
pushes this measure in this grid.
|
|
420
|
+
Input
|
|
421
|
+
-----
|
|
422
|
+
- pts: of the form array[int, ndim=2]
|
|
423
|
+
- weights: array[int, ndim=1]
|
|
424
|
+
- grid of the form Iterable[array[float, ndim=1]]
|
|
425
|
+
- num_parameters: number of parameters
|
|
426
|
+
"""
|
|
427
|
+
if pts.ndim != 2:
|
|
428
|
+
raise ValueError(f"invalid dirac locations. got {pts.ndim=} != 2")
|
|
429
|
+
if len(grid) == 0:
|
|
430
|
+
raise ValueError(f"Empty grid given. Got {grid=}")
|
|
431
|
+
cdef int num_parameters = pts.shape[1]
|
|
432
|
+
if mass_default is None:
|
|
433
|
+
api = api_from_tensors(*grid)
|
|
434
|
+
else:
|
|
435
|
+
api = api_from_tensors(*grid, mass_default)
|
|
436
|
+
|
|
437
|
+
_grid = list(grid)
|
|
438
|
+
_mass_default = None if mass_default is None else api.astensor(mass_default)
|
|
439
|
+
while len(_grid) < num_parameters:
|
|
440
|
+
_grid += [api.cat([
|
|
441
|
+
(gt:=api.astensor(g))[1:],
|
|
442
|
+
api.astensor(_inf_value(api.asnumpy(gt))).reshape(1)
|
|
443
|
+
]) for g in grid]
|
|
444
|
+
if mass_default is not None:
|
|
445
|
+
_mass_default = api.cat([_mass_default,mass_default])
|
|
446
|
+
grid = tuple(_grid)
|
|
447
|
+
mass_default = _mass_default
|
|
448
|
+
|
|
449
|
+
coords = evaluate_in_grid(np.asarray(pts, dtype=int), grid, mass_default)
|
|
450
|
+
return (coords, weights)
|
|
451
|
+
|
|
452
|
+
# TODO : optimize with memoryviews / typing
|
|
453
|
+
def sms_in_grid(sms, grid, mass_default=None):
|
|
454
|
+
"""Given a measure whose points are coordinates,
|
|
455
|
+
pushes this measure in this grid.
|
|
456
|
+
Input
|
|
457
|
+
-----
|
|
458
|
+
- sms: of the form (signed_measure_like for num_measures)
|
|
459
|
+
where signed_measure_like = tuple(array[int, ndim=2], array[int])
|
|
460
|
+
- grid of the form Iterable[array[float, ndim=1]]
|
|
461
|
+
"""
|
|
462
|
+
sms = tuple(sm_in_grid(pts,weights,grid=grid, mass_default=mass_default) for pts,weights in sms)
|
|
463
|
+
return sms
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _push_pts_to_line(pts, basepoint, direction=None, api=None):
|
|
467
|
+
if api is None:
|
|
468
|
+
api = api_from_tensors(pts, basepoint)
|
|
469
|
+
pts = api.astensor(pts)
|
|
470
|
+
basepoint = api.astensor(basepoint)
|
|
471
|
+
num_parameters = basepoint.shape[0]
|
|
472
|
+
if direction is not None:
|
|
473
|
+
if not api.is_promotable(direction):
|
|
474
|
+
raise ValueError(f"Incompatible input types. Got {type(pts)=}, {type(basepoint)=}, {type(direction)=}")
|
|
475
|
+
|
|
476
|
+
direction = api.astensor(direction)
|
|
477
|
+
ok_idx = direction > 0
|
|
478
|
+
if ok_idx.sum() == 0:
|
|
479
|
+
raise ValueError(f"Got invalid direction {direction}")
|
|
480
|
+
zero_idx = None if ok_idx.all() else direction == 0
|
|
481
|
+
else:
|
|
482
|
+
direction = api.tensor([1], dtype=int)
|
|
483
|
+
ok_idx = slice(None)
|
|
484
|
+
zero_idx = None
|
|
485
|
+
xa = api.maxvalues(
|
|
486
|
+
(pts[:, ok_idx] - basepoint[ok_idx]) / direction[ok_idx], axis=1, keepdims=True
|
|
487
|
+
)
|
|
488
|
+
if zero_idx is not None:
|
|
489
|
+
xb = api.where(pts[:, zero_idx] <= basepoint[zero_idx], -np.inf, np.inf)
|
|
490
|
+
xs = api.maxvalues(api.cat([xa, xb], axis=1), axis=1, keepdims=True)
|
|
491
|
+
else:
|
|
492
|
+
xs = xa
|
|
493
|
+
return xs.squeeze()
|
|
494
|
+
|
|
495
|
+
def _push_pts_to_lines(pts, basepoints, directions=None, api=None):
|
|
496
|
+
if api is None:
|
|
497
|
+
api = api_from_tensors(pts,basepoints)
|
|
498
|
+
cdef int num_lines = len(basepoints)
|
|
499
|
+
cdef int num_pts = len(pts)
|
|
500
|
+
|
|
501
|
+
pts = api.astensor(pts)
|
|
502
|
+
basepoints = api.astensor(basepoints)
|
|
503
|
+
if directions is None:
|
|
504
|
+
directions = [None]*num_lines
|
|
505
|
+
else:
|
|
506
|
+
directions = api.astensor(directions)
|
|
507
|
+
|
|
508
|
+
out = api.empty((num_lines, num_pts), dtype=pts.dtype)
|
|
509
|
+
for i in range(num_lines):
|
|
510
|
+
out[i] = _push_pts_to_line(pts, basepoints[i], directions[i], api=api)[None]
|
|
511
|
+
return out
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def evaluate_mod_in_grid(mod, grid, box=None):
|
|
515
|
+
"""Given an MMA module, pushes it into the specified grid.
|
|
516
|
+
Useful for e.g., make it differentiable.
|
|
517
|
+
|
|
518
|
+
Input
|
|
519
|
+
-----
|
|
520
|
+
- mod: PyModule
|
|
521
|
+
- grid: Iterable of 1d array, for num_parameters
|
|
522
|
+
Ouput
|
|
523
|
+
-----
|
|
524
|
+
torch-compatible module in the format:
|
|
525
|
+
(num_degrees) x (num_interval of degree) x ((num_birth, num_parameter), (num_death, num_parameters))
|
|
526
|
+
|
|
527
|
+
"""
|
|
528
|
+
(birth_sizes, death_sizes), births, deaths = mod.to_flat_idx(grid)
|
|
529
|
+
births = evaluate_in_grid(births, grid)
|
|
530
|
+
deaths = evaluate_in_grid(deaths, grid)
|
|
531
|
+
api = api_from_tensors(births, deaths)
|
|
532
|
+
diff_mod = tuple(
|
|
533
|
+
zip(
|
|
534
|
+
api.split_with_sizes(births,birth_sizes.tolist()),
|
|
535
|
+
api.split_with_sizes(deaths,death_sizes.tolist()),
|
|
536
|
+
)
|
|
537
|
+
)
|
|
538
|
+
return diff_mod
|