QPromaQ commited on
Commit
5b8d38b
·
verified ·
1 Parent(s): 84e1395

Reset repository and upload final project (part 23)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +33 -0
  2. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ctest.cpython-312-darwin.so +0 -0
  3. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_cytest.cpython-312-darwin.so +0 -0
  4. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_delegators.py +303 -0
  5. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_filters.py +2422 -0
  6. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_fourier.py +306 -0
  7. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_interpolation.py +1033 -0
  8. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_measurements.py +1689 -0
  9. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_morphology.py +0 -0
  10. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-darwin.so +3 -0
  11. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ndimage_api.py +16 -0
  12. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ni_docstrings.py +214 -0
  13. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-darwin.so +3 -0
  14. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ni_support.py +139 -0
  15. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_rank_filter_1d.cpython-312-darwin.so +0 -0
  16. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_support_alternative_backends.py +120 -0
  17. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/filters.py +27 -0
  18. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/fourier.py +21 -0
  19. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/interpolation.py +22 -0
  20. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/measurements.py +24 -0
  21. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/morphology.py +27 -0
  22. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/.___init__.py +0 -0
  23. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/.___pycache__ +0 -0
  24. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._data +0 -0
  25. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._dots.png +3 -0
  26. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_c_api.py +0 -0
  27. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_datatypes.py +0 -0
  28. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_filters.py +0 -0
  29. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_fourier.py +0 -0
  30. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_interpolation.py +0 -0
  31. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_measurements.py +0 -0
  32. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_morphology.py +0 -0
  33. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_ni_support.py +0 -0
  34. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_splines.py +0 -0
  35. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/__init__.py +12 -0
  36. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/._label_inputs.txt +0 -0
  37. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/._label_results.txt +0 -0
  38. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/._label_strels.txt +0 -0
  39. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_inputs.txt +21 -0
  40. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_results.txt +294 -0
  41. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_strels.txt +42 -0
  42. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/dots.png +3 -0
  43. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_c_api.py +102 -0
  44. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_datatypes.py +67 -0
  45. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_filters.py +0 -0
  46. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_fourier.py +197 -0
  47. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_interpolation.py +1499 -0
  48. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_measurements.py +1696 -0
  49. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_morphology.py +0 -0
  50. .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_ni_support.py +77 -0
.gitattributes CHANGED
@@ -155,3 +155,36 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
155
  .venv_haddock/lib/python3.12/site-packages/scipy/linalg/_solve_toeplitz.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
156
  .venv_haddock/lib/python3.12/site-packages/scipy/linalg/cython_blas.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
157
  .venv_haddock/lib/python3.12/site-packages/scipy/linalg/cython_lapack.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  .venv_haddock/lib/python3.12/site-packages/scipy/linalg/_solve_toeplitz.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
156
  .venv_haddock/lib/python3.12/site-packages/scipy/linalg/cython_blas.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
157
  .venv_haddock/lib/python3.12/site-packages/scipy/linalg/cython_lapack.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
158
+ .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
159
+ .venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
160
+ .venv_haddock/lib/python3.12/site-packages/scipy/odr/__odrpack.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
161
+ .venv_haddock/lib/python3.12/site-packages/scipy/optimize/_bglu_dense.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
162
+ .venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/_core.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
163
+ .venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_options.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
164
+ .venv_haddock/lib/python3.12/site-packages/scipy/optimize/_minpack.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
165
+ .venv_haddock/lib/python3.12/site-packages/scipy/optimize/_moduleTNC.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
166
+ .venv_haddock/lib/python3.12/site-packages/scipy/optimize/_pava_pybind.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
167
+ .venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trlib/_trlib.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
168
+ .venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
169
+ .venv_haddock/lib/python3.12/site-packages/scipy/signal/_peak_finding_utils.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
170
+ .venv_haddock/lib/python3.12/site-packages/scipy/signal/_sigtools.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
171
+ .venv_haddock/lib/python3.12/site-packages/scipy/signal/_sosfilt.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
172
+ .venv_haddock/lib/python3.12/site-packages/scipy/signal/_upfirdn_apply.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
173
+ .venv_haddock/lib/python3.12/site-packages/scipy/sparse/_csparsetools.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
174
+ .venv_haddock/lib/python3.12/site-packages/scipy/sparse/_sparsetools.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
175
+ .venv_haddock/lib/python3.12/site-packages/scipy/sparse/csgraph/_flow.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
176
+ .venv_haddock/lib/python3.12/site-packages/scipy/sparse/csgraph/_matching.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
177
+ .venv_haddock/lib/python3.12/site-packages/scipy/sparse/csgraph/_min_spanning_tree.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
178
+ .venv_haddock/lib/python3.12/site-packages/scipy/sparse/csgraph/_reordering.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
179
+ .venv_haddock/lib/python3.12/site-packages/scipy/sparse/csgraph/_shortest_path.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
180
+ .venv_haddock/lib/python3.12/site-packages/scipy/sparse/csgraph/_tools.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
181
+ .venv_haddock/lib/python3.12/site-packages/scipy/sparse/csgraph/_traversal.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
182
+ .venv_haddock/lib/python3.12/site-packages/scipy/sparse/linalg/_dsolve/_superlu.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
183
+ .venv_haddock/lib/python3.12/site-packages/scipy/sparse/linalg/_eigen/arpack/_arpacklib.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
184
+ .venv_haddock/lib/python3.12/site-packages/scipy/sparse/linalg/_propack.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
185
+ .venv_haddock/lib/python3.12/site-packages/scipy/spatial/_ckdtree.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
186
+ .venv_haddock/lib/python3.12/site-packages/scipy/spatial/_distance_pybind.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
187
+ .venv_haddock/lib/python3.12/site-packages/scipy/spatial/_distance_wrap.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
188
+ .venv_haddock/lib/python3.12/site-packages/scipy/spatial/_qhull.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
189
+ .venv_haddock/lib/python3.12/site-packages/scipy/spatial/transform/_rigid_transform_cy.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
190
+ .venv_haddock/lib/python3.12/site-packages/scipy/spatial/transform/_rotation_cy.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ctest.cpython-312-darwin.so ADDED
Binary file (51.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_cytest.cpython-312-darwin.so ADDED
Binary file (96.4 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_delegators.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Delegators for alternative backends in scipy.ndimage.
2
+
3
+ The signature of `func_signature` must match the signature of ndimage.func.
4
+ The job of a `func_signature` is to know which arguments of `ndimage.func`
5
+ are arrays.
6
+
7
+ * signatures are generated by
8
+
9
+ --------------
10
+ import inspect
11
+ from scipy import ndimage
12
+
13
+ names = [x for x in dir(ndimage) if not x.startswith('_')]
14
+ objs = [getattr(ndimage, name) for name in names]
15
+ funcs = [obj for obj in objs if inspect.isroutine(obj)]
16
+
17
+ for func in funcs:
18
+ sig = inspect.signature(func)
19
+ print(f"def {func.__name__}_signature{sig}:\n\tpass\n\n")
20
+ ---------------
21
+
22
+ * which arguments to delegate on: manually trawled the documentation for
23
+ array-like and array arguments
24
+
25
+ """
26
+ import numpy as np
27
+ from scipy._lib._array_api import array_namespace
28
+ from scipy.ndimage._ni_support import _skip_if_dtype
29
+
30
+
31
+ def affine_transform_signature(
32
+ input, matrix, offset=0.0, output_shape=None, output=None, *args, **kwds
33
+ ):
34
+ return array_namespace(input, matrix, _skip_if_dtype(output))
35
+
36
+
37
+ def binary_closing_signature(
38
+ input, structure=None, iterations=1, output=None, *args, **kwds
39
+ ):
40
+ return array_namespace(input, structure, _skip_if_dtype(output))
41
+
42
+ binary_opening_signature = binary_closing_signature
43
+
44
+
45
+ def binary_dilation_signature(
46
+ input, structure=None, iterations=1, mask=None, output=None, *args, **kwds
47
+ ):
48
+ return array_namespace(input, structure, _skip_if_dtype(output), mask)
49
+
50
+ binary_erosion_signature = binary_dilation_signature
51
+
52
+
53
+ def binary_fill_holes_signature(
54
+ input, structure=None, output=None, origin=0, *args, **kwargs
55
+ ):
56
+ return array_namespace(input, structure, _skip_if_dtype(output))
57
+
58
+
59
+ def label_signature(input, structure=None, output=None, origin=0):
60
+ return array_namespace(input, structure, _skip_if_dtype(output))
61
+
62
+
63
+ def binary_hit_or_miss_signature(
64
+ input, structure1=None, structure2=None, output=None, *args, **kwds
65
+ ):
66
+ return array_namespace(input, structure1, structure2, _skip_if_dtype(output))
67
+
68
+
69
+ def binary_propagation_signature(
70
+ input, structure=None, mask=None, output=None, *args, **kwds
71
+ ):
72
+ return array_namespace(input, structure, mask, _skip_if_dtype(output))
73
+
74
+
75
+ def convolve_signature(input, weights, output=None, *args, **kwds):
76
+ return array_namespace(input, weights, _skip_if_dtype(output))
77
+
78
+ correlate_signature = convolve_signature
79
+
80
+
81
+ def convolve1d_signature(input, weights, axis=-1, output=None, *args, **kwds):
82
+ return array_namespace(input, weights, _skip_if_dtype(output))
83
+
84
+ correlate1d_signature = convolve1d_signature
85
+
86
+
87
+ def distance_transform_bf_signature(
88
+ input, metric='euclidean', sampling=None, return_distances=True,
89
+ return_indices=False, distances=None, indices=None
90
+ ):
91
+ return array_namespace(input, distances, indices)
92
+
93
+
94
+ def distance_transform_cdt_signature(
95
+ input, metric='chessboard', return_distances=True, return_indices=False,
96
+ distances=None, indices=None
97
+ ):
98
+ return array_namespace(input, distances, indices)
99
+
100
+
101
+ def distance_transform_edt_signature(
102
+ input, sampling=None, return_distances=True, return_indices=False,
103
+ distances=None, indices=None
104
+ ):
105
+ return array_namespace(input, distances, indices)
106
+
107
+
108
+ def find_objects_signature(input, max_label=0):
109
+ return array_namespace(input)
110
+
111
+
112
+ def fourier_ellipsoid_signature(input, size, n=-1, axis=-1, output=None):
113
+ return array_namespace(input, _skip_if_dtype(output))
114
+
115
+ fourier_uniform_signature = fourier_ellipsoid_signature
116
+
117
+
118
+ def fourier_gaussian_signature(input, sigma, n=-1, axis=-1, output=None):
119
+ return array_namespace(input, _skip_if_dtype(output))
120
+
121
+ def fourier_shift_signature(input, shift, n=-1, axis=-1, output=None):
122
+ return array_namespace(input, _skip_if_dtype(output))
123
+
124
+
125
+ def gaussian_filter_signature(input, sigma, order=0, output=None, *args, **kwds):
126
+ return array_namespace(input, _skip_if_dtype(output))
127
+
128
+
129
+ def gaussian_filter1d_signature(
130
+ input, sigma, axis=-1, order=0, output=None, *args, **kwds
131
+ ):
132
+ return array_namespace(input, _skip_if_dtype(output))
133
+
134
+
135
+ def gaussian_gradient_magnitude_signature(input, sigma, output=None, *args, **kwds):
136
+ return array_namespace(input, _skip_if_dtype(output))
137
+
138
+ gaussian_laplace_signature = gaussian_gradient_magnitude_signature
139
+
140
+
141
+ def generate_binary_structure_signature(rank, connectivity):
142
+ # XXX: no input arrays; always return numpy
143
+ return np
144
+
145
+
146
+ def generic_filter_signature(
147
+ input, function, size=None, footprint=None, output=None, *args, **kwds
148
+ ):
149
+ # XXX: function LowLevelCallable w/backends
150
+ return array_namespace(input, footprint, _skip_if_dtype(output))
151
+
152
+
153
+ def generic_filter1d_signature(
154
+ input, function, filter_size, axis=-1, output=None, *args, **kwds
155
+ ):
156
+ return array_namespace(input, _skip_if_dtype(output))
157
+
158
+
159
+ def generic_gradient_magnitude_signature(
160
+ input, derivative, output=None, *args, **kwds
161
+ ):
162
+ # XXX: function LowLevelCallable w/backends
163
+ return array_namespace(input, _skip_if_dtype(output))
164
+
165
+
166
+ def generic_laplace_signature(input, derivative2, output=None, *args, **kwds):
167
+ # XXX: function LowLevelCallable w/backends
168
+ return array_namespace(input, _skip_if_dtype(output))
169
+
170
+
171
+ def geometric_transform_signature(
172
+ input, mapping, output_shape=None, output=None, *args, **kwds
173
+ ):
174
+ return array_namespace(input, _skip_if_dtype(output))
175
+
176
+
177
+ def histogram_signature(input, min, max, bins, labels=None, index=None):
178
+ return array_namespace(input, labels)
179
+
180
+
181
+ def iterate_structure_signature(structure, iterations, origin=None):
182
+ return array_namespace(structure)
183
+
184
+
185
+ def labeled_comprehension_signature(input, labels, *args, **kwds):
186
+ return array_namespace(input, labels)
187
+
188
+
189
+ def laplace_signature(input, output=None, *args, **kwds):
190
+ return array_namespace(input, _skip_if_dtype(output))
191
+
192
+
193
+ def map_coordinates_signature(input, coordinates, output=None, *args, **kwds):
194
+ return array_namespace(input, coordinates, _skip_if_dtype(output))
195
+
196
+
197
+ def maximum_filter1d_signature(input, size, axis=-1, output=None, *args, **kwds):
198
+ return array_namespace(input, _skip_if_dtype(output))
199
+
200
+ minimum_filter1d_signature = maximum_filter1d_signature
201
+ uniform_filter1d_signature = maximum_filter1d_signature
202
+
203
+
204
+ def maximum_signature(input, labels=None, index=None):
205
+ return array_namespace(input, labels, index)
206
+
207
+ minimum_signature = maximum_signature
208
+ median_signature = maximum_signature
209
+ mean_signature = maximum_signature
210
+ variance_signature = maximum_signature
211
+ standard_deviation_signature = maximum_signature
212
+ sum_labels_signature = maximum_signature
213
+ sum_signature = maximum_signature # ndimage.sum is sum_labels
214
+
215
+ maximum_position_signature = maximum_signature
216
+ minimum_position_signature = maximum_signature
217
+
218
+ extrema_signature = maximum_signature
219
+ center_of_mass_signature = extrema_signature
220
+
221
+
222
+ def median_filter_signature(
223
+ input, size=None, footprint=None, output=None, *args, **kwds
224
+ ):
225
+ return array_namespace(input, footprint, _skip_if_dtype(output))
226
+
227
+ minimum_filter_signature = median_filter_signature
228
+ maximum_filter_signature = median_filter_signature
229
+
230
+
231
+ def morphological_gradient_signature(
232
+ input, size=None, footprint=None, structure=None, output=None, *args, **kwds
233
+ ):
234
+ return array_namespace(input, footprint, structure, _skip_if_dtype(output))
235
+
236
+ morphological_laplace_signature = morphological_gradient_signature
237
+ white_tophat_signature = morphological_gradient_signature
238
+ black_tophat_signature = morphological_gradient_signature
239
+ grey_closing_signature = morphological_gradient_signature
240
+ grey_dilation_signature = morphological_gradient_signature
241
+ grey_erosion_signature = morphological_gradient_signature
242
+ grey_opening_signature = morphological_gradient_signature
243
+
244
+
245
+ def percentile_filter_signature(
246
+ input, percentile, size=None, footprint=None, output=None, *args, **kwds
247
+ ):
248
+ return array_namespace(input, footprint, _skip_if_dtype(output))
249
+
250
+
251
+ def prewitt_signature(input, axis=-1, output=None, *args, **kwds):
252
+ return array_namespace(input, _skip_if_dtype(output))
253
+
254
+ sobel_signature = prewitt_signature
255
+
256
+
257
+ def rank_filter_signature(
258
+ input, rank, size=None, footprint=None, output=None, *args, **kwds
259
+ ):
260
+ return array_namespace(input, footprint, _skip_if_dtype(output))
261
+
262
+
263
+ def rotate_signature(
264
+ input, angle, axes=(1, 0), reshape=True, output=None , *args, **kwds
265
+ ):
266
+ return array_namespace(input, _skip_if_dtype(output))
267
+
268
+
269
+ def shift_signature(input, shift, output=None, *args, **kwds):
270
+ return array_namespace(input, _skip_if_dtype(output))
271
+
272
+
273
+ def spline_filter_signature(input, order=3, output=np.float64, *args, **kwds):
274
+ return array_namespace(input, _skip_if_dtype(output))
275
+
276
+
277
+ def spline_filter1d_signature(
278
+ input, order=3, axis=-1, output=np.float64, *args, **kwds
279
+ ):
280
+ return array_namespace(input, _skip_if_dtype(output))
281
+
282
+
283
+ def uniform_filter_signature(input, size=3, output=None, *args, **kwds):
284
+ return array_namespace(input, _skip_if_dtype(output))
285
+
286
+
287
+ def value_indices_signature(arr, *args, **kwds):
288
+ return array_namespace(arr)
289
+
290
+
291
+ def vectorized_filter_signature(
292
+ input, function, size=None, footprint=None, output=None, *args, **kwds
293
+ ):
294
+ return array_namespace(input, footprint, _skip_if_dtype(output))
295
+
296
+
297
+ def watershed_ift_signature(input, markers, structure=None, output=None):
298
+ return array_namespace(input, markers, structure, _skip_if_dtype(output))
299
+
300
+
301
+ def zoom_signature(input, zoom, output=None, *args, **kwds):
302
+ return array_namespace(input, _skip_if_dtype(output))
303
+
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_filters.py ADDED
@@ -0,0 +1,2422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2003-2005 Peter J. Verveer
2
+ #
3
+ # Redistribution and use in source and binary forms, with or without
4
+ # modification, are permitted provided that the following conditions
5
+ # are met:
6
+ #
7
+ # 1. Redistributions of source code must retain the above copyright
8
+ # notice, this list of conditions and the following disclaimer.
9
+ #
10
+ # 2. Redistributions in binary form must reproduce the above
11
+ # copyright notice, this list of conditions and the following
12
+ # disclaimer in the documentation and/or other materials provided
13
+ # with the distribution.
14
+ #
15
+ # 3. The name of the author may not be used to endorse or promote
16
+ # products derived from this software without specific prior
17
+ # written permission.
18
+ #
19
+ # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
20
+ # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21
+ # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
23
+ # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
25
+ # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
27
+ # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28
+ # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29
+ # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
+
31
+ from collections.abc import Iterable
32
+ import numbers
33
+ import warnings
34
+ import numpy as np
35
+ import operator
36
+ import math
37
+
38
+ from scipy._lib._util import normalize_axis_index
39
+ from scipy._lib._array_api import array_namespace, is_cupy, xp_size
40
+ from . import _ni_support
41
+ from . import _nd_image
42
+ from . import _ni_docstrings
43
+ from . import _rank_filter_1d
44
+
45
+ __all__ = ['correlate1d', 'convolve1d', 'gaussian_filter1d', 'gaussian_filter',
46
+ 'prewitt', 'sobel', 'generic_laplace', 'laplace',
47
+ 'gaussian_laplace', 'generic_gradient_magnitude',
48
+ 'gaussian_gradient_magnitude', 'correlate', 'convolve',
49
+ 'uniform_filter1d', 'uniform_filter', 'minimum_filter1d',
50
+ 'maximum_filter1d', 'minimum_filter', 'maximum_filter',
51
+ 'rank_filter', 'median_filter', 'percentile_filter',
52
+ 'generic_filter1d', 'generic_filter', 'vectorized_filter']
53
+
54
+
55
+ def _vectorized_filter_iv(input, function, size, footprint, output, mode, cval, origin,
56
+ axes, batch_memory):
57
+ xp = array_namespace(input, footprint, output)
58
+
59
+ # vectorized_filter input validation and standardization
60
+ input = xp.asarray(input)
61
+
62
+ if not callable(function):
63
+ raise ValueError("`function` must be a callable.")
64
+
65
+ if size is None and footprint is None:
66
+ raise ValueError("Either `size` or `footprint` must be provided.")
67
+
68
+ if size is not None and footprint is not None:
69
+ raise ValueError("Either `size` or `footprint` may be provided, not both.")
70
+
71
+ if axes is None:
72
+ axes = tuple(range(-input.ndim, 0))
73
+ elif np.isscalar(axes):
74
+ axes = (axes,)
75
+ n_axes = len(axes)
76
+ n_batch = input.ndim - n_axes
77
+
78
+ if n_axes > input.ndim:
79
+ message = ("The length of `axes` may not exceed the dimensionality of `input`"
80
+ "(`input.ndim`).")
81
+ raise ValueError(message)
82
+
83
+ # Either footprint or size must be provided
84
+ footprinted_function = function
85
+ if size is not None:
86
+ # If provided, size must be an integer or tuple of integers.
87
+ size = (size,)*n_axes if np.isscalar(size) else tuple(size)
88
+ valid = [xp.isdtype(xp.asarray(i).dtype, 'integral') and i > 0 for i in size]
89
+ if not all(valid):
90
+ raise ValueError("All elements of `size` must be positive integers.")
91
+ else:
92
+ # If provided, `footprint` must be array-like
93
+ footprint = xp.asarray(footprint, dtype=xp.bool)
94
+ size = footprint.shape
95
+ def footprinted_function(input, *args, axis=-1, **kwargs):
96
+ return function(input[..., footprint], *args, axis=-1, **kwargs)
97
+
98
+ # And by now, the dimensionality of the footprint must equal the number of axes
99
+ if n_axes != len(size):
100
+ message = ("`axes` must be compatible with the dimensionality "
101
+ "of the window specified by `size` or `footprint`.")
102
+ raise ValueError(message)
103
+
104
+ # If this is not *equal* to the dimensionality of `input`, then `axes`
105
+ # must be a provided tuple, and its length must equal the core dimensionality.
106
+ elif n_axes < input.ndim:
107
+ if axes is None:
108
+ message = ("`axes` must be provided if the dimensionality of the window "
109
+ "(`len(size)` or `footprint.ndim`) does not equal the number "
110
+ "of axes of `input` (`input.ndim`).")
111
+ raise ValueError(message)
112
+ else:
113
+ axes = tuple(range(-n_axes, 0)) if axes is None else axes
114
+
115
+ axes = (axes,) if np.isscalar(axes) else axes
116
+
117
+ # If `origin` is provided, then it must be "broadcastable" to a tuple with length
118
+ # equal to the core dimensionality.
119
+ if origin is None:
120
+ origin = (0,) * n_axes
121
+ else:
122
+ origin = (origin,)*n_axes if np.isscalar(origin) else tuple(origin)
123
+ integral = [xp.isdtype(xp.asarray(i).dtype, 'integral') for i in origin]
124
+ if not all(integral):
125
+ raise ValueError("All elements of `origin` must be integers.")
126
+ if not len(origin) == n_axes:
127
+ message = ("`origin` must be an integer or tuple of integers with length "
128
+ "equal to the number of axes.")
129
+ raise ValueError(message)
130
+
131
+ # mode must be one of the allowed strings, and we should convert it to the
132
+ # value required by `np.pad`/`cp.pad` here.
133
+ valid_modes = {'reflect', 'constant', 'nearest', 'mirror', 'wrap',
134
+ 'grid-mirror', 'grid-constant', 'grid-wrap', 'valid'}
135
+ if mode not in valid_modes:
136
+ raise ValueError(f"`mode` must be one of {valid_modes}.")
137
+ mode_map = {'nearest': 'edge', 'reflect': 'symmetric', 'mirror': 'reflect',
138
+ 'grid-mirror': 'reflect', 'grid-constant': 'constant',
139
+ 'grid-wrap': 'wrap'}
140
+ mode = mode_map.get(mode, mode)
141
+
142
+ if mode == 'valid' and any(origin):
143
+ raise ValueError("`mode='valid'` is incompatible with use of `origin`.")
144
+
145
+ if cval is None:
146
+ cval = 0.0
147
+ elif mode != 'constant':
148
+ raise ValueError("Use of `cval` is compatible only with `mode='constant'`.")
149
+
150
+ # `cval` must be a scalar or "broadcastable" to a tuple with the same
151
+ # dimensionality of `input`. (Full input validation done by `np.pad`/`cp.pad`.)
152
+ if not xp.isdtype(xp.asarray(cval).dtype, 'numeric'):
153
+ raise ValueError("`cval` must include only numbers.")
154
+
155
+ # `batch_memory` must be a positive number.
156
+ temp = xp.asarray(batch_memory)
157
+ if temp.ndim != 0 or (not xp.isdtype(temp.dtype, 'numeric')) or temp <= 0:
158
+ raise ValueError("`batch_memory` must be positive number.")
159
+
160
+ # For simplicity, work with `axes` at the end.
161
+ working_axes = tuple(range(-n_axes, 0))
162
+ input = xp.moveaxis(input, axes, working_axes)
163
+ output = (xp.moveaxis(output, axes, working_axes)
164
+ if output is not None else output)
165
+
166
+ # Wrap the function to limit maximum memory usage, deal with `footprint`,
167
+ # and populate `output`. The latter requires some verbosity because we
168
+ # don't know the output dtype.
169
+ def wrapped_function(view, output=output):
170
+ kwargs = {'axis': working_axes}
171
+
172
+ if working_axes == ():
173
+ return footprinted_function(xp.asarray(view), **kwargs)
174
+
175
+ # for now, assume we only have to iterate over zeroth axis
176
+ chunk_size = math.prod(view.shape[1:]) * view.dtype.itemsize
177
+ slices_per_batch = min(view.shape[0], batch_memory // chunk_size)
178
+ if slices_per_batch < 1:
179
+ raise ValueError("`batch_memory` is insufficient for minimum chunk size.")
180
+
181
+ elif slices_per_batch == view.shape[0]:
182
+ if output is None:
183
+ return footprinted_function(xp.asarray(view), **kwargs)
184
+ else:
185
+ output[...] = footprinted_function(xp.asarray(view), **kwargs)
186
+ return output
187
+
188
+ for i in range(0, view.shape[0], slices_per_batch):
189
+ i2 = min(i + slices_per_batch, view.shape[0])
190
+ if output is None:
191
+ # Look at the dtype before allocating the array. (In a follow-up, we
192
+ # can also look at the shape to support non-scalar elements.)
193
+ temp = footprinted_function(xp.asarray(view[i:i2]), **kwargs)
194
+ output = xp.empty(view.shape[:-n_axes], dtype=temp.dtype)
195
+ output[i:i2, ...] = temp
196
+ else:
197
+ output[i:i2, ...] = footprinted_function(xp.asarray(view[i:i2]),
198
+ **kwargs)
199
+ return output
200
+
201
+ return (input, wrapped_function, size, mode, cval, origin,
202
+ working_axes, axes, n_axes, n_batch, xp)
203
+
204
+
205
+ @_ni_docstrings.docfiller
206
+ def vectorized_filter(input, function, *, size=None, footprint=None, output=None,
207
+ mode='reflect', cval=None, origin=None, axes=None,
208
+ batch_memory=2**30):
209
+ """Filter an array with a vectorized Python callable as the kernel
210
+
211
+ Parameters
212
+ ----------
213
+ %(input)s
214
+ function : callable
215
+ Kernel to apply over a window centered at each element of `input`.
216
+ Callable must have signature::
217
+
218
+ function(window: ndarray, *, axis: int | tuple) -> scalar
219
+
220
+ where ``axis`` specifies the axis (or axes) of ``window`` along which
221
+ the filter function is evaluated.
222
+ size : scalar or tuple, optional
223
+ See `footprint` below. Ignored if `footprint` is given.
224
+ footprint : array, optional
225
+ Either `size` or `footprint` must be defined. `size` gives
226
+ the shape that is taken from the input array, at every element
227
+ position, to define the input to the filter function.
228
+ `footprint` is a boolean array that specifies (implicitly) a
229
+ shape, but also which of the elements within this shape will get
230
+ passed to the filter function. Thus ``size=(n, m)`` is equivalent
231
+ to ``footprint=np.ones((n, m))``.
232
+ We adjust `size` to the number of dimensions indicated by `axes`.
233
+ For instance, if `axes` is ``(0, 2, 1)`` and ``n`` is passed for ``size``,
234
+ then the effective `size` is ``(n, n, n)``.
235
+ output : array, optional
236
+ The array in which to place the output. By default, an array of the dtype
237
+ returned by `function` will be created.
238
+ mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
239
+ The `mode` parameter determines how the input array is extended
240
+ beyond its boundaries. Default is 'reflect'. Behavior for each valid
241
+ value is as follows:
242
+
243
+ 'reflect' (`d c b a | a b c d | d c b a`)
244
+ The input is extended by reflecting about the edge of the last
245
+ pixel. This mode is also sometimes referred to as half-sample
246
+ symmetric.
247
+
248
+ 'constant' (`k k k k | a b c d | k k k k`)
249
+ The input is extended by filling all values beyond the edge with
250
+ the same constant value, defined by the `cval` parameter.
251
+
252
+ 'nearest' (`a a a a | a b c d | d d d d`)
253
+ The input is extended by replicating the last pixel.
254
+
255
+ 'mirror' (`d c b | a b c d | c b a`)
256
+ The input is extended by reflecting about the center of the last
257
+ pixel. This mode is also sometimes referred to as whole-sample
258
+ symmetric.
259
+
260
+ 'wrap' (`a b c d | a b c d | a b c d`)
261
+ The input is extended by wrapping around to the opposite edge.
262
+
263
+ 'valid' (`| a b c d |`)
264
+ The input is not extended; rather, the output shape is reduced depending
265
+ on the window size according to the following calculation::
266
+
267
+ window_size = np.asarray(size if size is not None else footprint.shape)
268
+ output_shape = np.asarray(input.shape)
269
+ output_shape[np.asarray(axes)] -= (window_size - 1)
270
+
271
+ %(cval)s
272
+ %(origin_multiple)s
273
+ axes : tuple of int, optional
274
+ If None, `input` is filtered along all axes. Otherwise, `input` is filtered
275
+ along the specified axes. When `axes` is specified, the dimensionality of
276
+ `footprint` and the length of any tuples used for `size` or `origin` must
277
+ match the length of `axes`. The ith axis of `footprint` and the ith element
278
+ in these tuples corresponds to the ith element of `axes`.
279
+ batch_memory : int, default: 2**30
280
+ The maximum number of bytes occupied by data in the ``window``
281
+ array passed to ``function``.
282
+
283
+ Returns
284
+ -------
285
+ output : ndarray
286
+ Filtered array. The dtype is the output dtype of `function`. If `function` is
287
+ scalar-valued when applied to a single window, the shape of the output is that
288
+ of `input` (unless ``mode=='valid'``; see `mode` documentation). If `function`
289
+ is multi-valued when applied to a single window, the placement of the
290
+ corresponding dimensions within the output shape depends entirely on the
291
+ behavior of `function`; see Examples.
292
+
293
+ See Also
294
+ --------
295
+ scipy.ndimage.generic_filter
296
+
297
+ Notes
298
+ -----
299
+ This function works by padding `input` according to `mode`, then calling the
300
+ provided `function` on chunks of a sliding window view over the padded array.
301
+ This approach is very simple and flexible, and so the function has many features
302
+ not offered by some other filter functions (e.g. memory control, ``float16``
303
+ and complex dtype support, and any NaN-handling features provided by the
304
+ `function` argument).
305
+
306
+ However, this brute-force approach may perform considerable redundant work.
307
+ Use a specialized filter (e.g. `minimum_filter` instead of this function with
308
+ `numpy.min` as the callable; `uniform_filter` instead of this function with
309
+ `numpy.mean` as the callable) when possible, as it may use a more efficient
310
+ algorithm.
311
+
312
+ When a specialized filter is not available, this function is ideal when `function`
313
+ is a vectorized, pure-Python callable. Even better performance may be possible
314
+ by passing a `scipy.LowLevelCallable` to `generic_filter`. `generic_filter` may
315
+ also be preferred for expensive callables with large filter footprints and
316
+ callables that are not vectorized (i.e. those without ``axis`` support).
317
+
318
+ This function does not provide the ``extra_arguments`` or ``extra_keywords``
319
+ arguments provided by some `ndimage` functions. There are two reasons:
320
+
321
+ - The passthrough functionality can be achieved by the user: simply wrap the
322
+ original callable in another function that provides the required arguments;
323
+ e.g., ``function=lambda input, axis: function(input, *extra_arguments, axis=axis, **extra_keywords)``.
324
+ - There are use cases for `function` to be passed additional *sliding-window data*
325
+ to `function` besides `input`. This is not yet implemented, but we reserve
326
+ these argument names for such a feature, which would add capability rather than
327
+ providing a duplicate interface to existing capability.
328
+
329
+ Examples
330
+ --------
331
+ Suppose we wish to perform a median filter with even window size on a ``float16``
332
+ image. Furthermore, the image has NaNs that we wish to be ignored (and effectively
333
+ removed by the filter). `median_filter` does not support ``float16`` data, its
334
+ behavior when NaNs are present is not defined, and for even window sizes, it does
335
+ not return the usual sample median - the average of the two middle elements. This
336
+ would be an excellent use case for `vectorized_filter` with
337
+ ``function=np.nanmedian``, which supports the required interface: it accepts a
338
+ data array of any shape as the first positional argument, and tuple of axes as
339
+ keyword argument ``axis``.
340
+
341
+ >>> import numpy as np
342
+ >>> from scipy import datasets, ndimage
343
+ >>> from scipy.ndimage import vectorized_filter
344
+ >>> import matplotlib.pyplot as plt
345
+ >>> ascent = ndimage.zoom(datasets.ascent(), 0.5).astype(np.float16)
346
+ >>> ascent[::16, ::16] = np.nan
347
+ >>> result = vectorized_filter(ascent, function=np.nanmedian, size=4)
348
+
349
+ Plot the original and filtered images.
350
+
351
+ >>> fig = plt.figure()
352
+ >>> plt.gray() # show the filtered result in grayscale
353
+ >>> ax1 = fig.add_subplot(121) # left side
354
+ >>> ax2 = fig.add_subplot(122) # right side
355
+ >>> ax1.imshow(ascent)
356
+ >>> ax2.imshow(result)
357
+ >>> fig.tight_layout()
358
+ >>> plt.show()
359
+
360
+ Another need satisfied by `vectorized_filter` is to perform multi-output
361
+ filters. For instance, suppose we wish to filter an image according to the 25th
362
+ and 75th percentiles in addition to the median. We could perform the three
363
+ filters separately.
364
+
365
+ >>> ascent = ndimage.zoom(datasets.ascent(), 0.5)
366
+ >>> def get_quantile_fun(p):
367
+ ... return lambda x, axis: np.quantile(x, p, axis=axis)
368
+ >>> ref1 = vectorized_filter(ascent, get_quantile_fun(0.25), size=4)
369
+ >>> ref2 = vectorized_filter(ascent, get_quantile_fun(0.50), size=4)
370
+ >>> ref3 = vectorized_filter(ascent, get_quantile_fun(0.75), size=4)
371
+ >>> ref = np.stack([ref1, ref2, ref3])
372
+
373
+ However, `vectorized_filter` also supports filters that return multiple outputs
374
+ as long as `output` is unspecified and `batch_memory` is sufficiently high to
375
+ perform the calculation in a single chunk.
376
+
377
+ >>> def quartiles(x, axis):
378
+ ... return np.quantile(x, [0.25, 0.50, 0.75], axis=axis)
379
+ >>> res = vectorized_filter(ascent, quartiles, size=4, batch_memory=np.inf)
380
+ >>> np.all(np.isclose(res, ref))
381
+ np.True_
382
+
383
+ The placement of the additional dimension(s) corresponding with multiple outputs
384
+ is at the discretion of `function`. `quartiles` happens to prepend one dimension
385
+ corresponding with the three outputs simply because that is the behavior of
386
+ `np.quantile`:
387
+
388
+ >>> res.shape == (3,) + ascent.shape
389
+ True
390
+
391
+ If we wished for this dimension to be appended:
392
+
393
+ >>> def quartiles(x, axis):
394
+ ... return np.moveaxis(np.quantile(x, [0.25, 0.50, 0.75], axis=axis), 0, -1)
395
+ >>> res = vectorized_filter(ascent, quartiles, size=4, batch_memory=np.inf)
396
+ >>> res.shape == ascent.shape + (3,)
397
+ True
398
+
399
+ Suppose we wish to implment a "mode" filter - a filter that selects the most
400
+ frequently occuring value within the window. A simple (but rather slow)
401
+ approach is to use `generic_filter` with `scipy.stats.mode`.
402
+
403
+ >>> from scipy import stats
404
+ >>> rng = np.random.default_rng(3195824598724609246)
405
+ >>> input = rng.integers(255, size=(50, 50)).astype(np.uint8)
406
+ >>> def simple_mode(input):
407
+ ... return stats.mode(input, axis=None).mode
408
+ >>> ref = ndimage.generic_filter(input, simple_mode, size=5)
409
+
410
+ If speed is important, `vectorized_filter` can take advantage of the performance
411
+ benefit of a vectorized callable.
412
+
413
+ >>> def vectorized_mode(x, axis=(-1,)):
414
+ ... n_axes = 1 if np.isscalar(axis) else len(axis)
415
+ ... x = np.moveaxis(x, axis, tuple(range(-n_axes, 0)))
416
+ ... x = np.reshape(x, x.shape[:-n_axes] + (-1,))
417
+ ... y = np.sort(x, axis=-1)
418
+ ... i = np.concatenate([np.ones(y.shape[:-1] + (1,), dtype=bool),
419
+ ... y[..., :-1] != y[..., 1:]], axis=-1)
420
+ ... indices = np.arange(y.size)[i.ravel()]
421
+ ... counts = np.diff(indices, append=y.size)
422
+ ... counts = np.reshape(np.repeat(counts, counts), y.shape)
423
+ ... k = np.argmax(counts, axis=-1, keepdims=True)
424
+ ... return np.take_along_axis(y, k, axis=-1)[..., 0]
425
+ >>> res = vectorized_filter(input, vectorized_mode, size=5)
426
+ >>> np.all(res == ref)
427
+ np.True_
428
+
429
+ Depending on the machine, the `vectorized_filter` version may be as much as
430
+ 100x faster.
431
+
432
+ """ # noqa: E501
433
+
434
+ (input, function, size, mode, cval, origin, working_axes, axes, n_axes, n_batch, xp
435
+ ) = _vectorized_filter_iv(input, function, size, footprint, output, mode, cval,
436
+ origin, axes, batch_memory)
437
+
438
+ # `np.pad`/`cp.pad` raises with these sorts of cases, but the best result is
439
+ # probably to return the original array. It could be argued that we should call
440
+ # the function on the empty array with `axis=None` just to determine the output
441
+ # dtype, but I can also see rationale against that.
442
+ if xp_size(input) == 0:
443
+ return xp.asarray(input)
444
+
445
+ # This seems to be defined.
446
+ if input.ndim == 0 and size == ():
447
+ return xp.asarray(function(input) if footprint is None
448
+ else function(input[footprint]))
449
+
450
+ if is_cupy(xp):
451
+ # CuPy is the only GPU backend that has `pad` (with all modes)
452
+ # and `sliding_window_view`. An enhancement would be to use
453
+ # no-copy conversion to CuPy whenever the data is on the GPU.
454
+ cp = xp # let there be no ambiguity!
455
+ swv = cp.lib.stride_tricks.sliding_window_view
456
+ pad = cp.pad
457
+ else:
458
+ # Try to perform no-copy conversion to NumPy for padding and
459
+ # `sliding_window_view`. (If that fails, fine - for now, the only
460
+ # GPU backend we support is CuPy.)
461
+ swv = np.lib.stride_tricks.sliding_window_view
462
+ pad = np.pad
463
+ input = np.asarray(input)
464
+ cval = np.asarray(cval)[()] if mode == 'constant' else None
465
+
466
+ # Border the image according to `mode` and `offset`.
467
+ if mode != 'valid':
468
+ kwargs = {'constant_values': cval} if mode == 'constant' else {}
469
+ borders = tuple((i//2 + j, (i-1)//2 - j) for i, j in zip(size, origin))
470
+ bordered_input = pad(input, ((0, 0),)*n_batch + borders, mode=mode, **kwargs)
471
+ else:
472
+ bordered_input = input
473
+
474
+ # Evaluate function with sliding window view. Function is already wrapped to
475
+ # manage memory, deal with `footprint`, populate `output`, etc.
476
+ view = swv(bordered_input, size, working_axes)
477
+ res = function(view)
478
+
479
+ # move working_axes back to original positions
480
+ return xp.moveaxis(res, working_axes, axes)
481
+
482
+
483
+ def _invalid_origin(origin, lenw):
484
+ return (origin < -(lenw // 2)) or (origin > (lenw - 1) // 2)
485
+
486
+
487
+ def _complex_via_real_components(func, input, weights, output, cval, **kwargs):
488
+ """Complex convolution via a linear combination of real convolutions."""
489
+ complex_input = input.dtype.kind == 'c'
490
+ complex_weights = weights.dtype.kind == 'c'
491
+ if complex_input and complex_weights:
492
+ # real component of the output
493
+ func(input.real, weights.real, output=output.real,
494
+ cval=np.real(cval), **kwargs)
495
+ output.real -= func(input.imag, weights.imag, output=None,
496
+ cval=np.imag(cval), **kwargs)
497
+ # imaginary component of the output
498
+ func(input.real, weights.imag, output=output.imag,
499
+ cval=np.real(cval), **kwargs)
500
+ output.imag += func(input.imag, weights.real, output=None,
501
+ cval=np.imag(cval), **kwargs)
502
+ elif complex_input:
503
+ func(input.real, weights, output=output.real, cval=np.real(cval),
504
+ **kwargs)
505
+ func(input.imag, weights, output=output.imag, cval=np.imag(cval),
506
+ **kwargs)
507
+ else:
508
+ if np.iscomplexobj(cval):
509
+ raise ValueError("Cannot provide a complex-valued cval when the "
510
+ "input is real.")
511
+ func(input, weights.real, output=output.real, cval=cval, **kwargs)
512
+ func(input, weights.imag, output=output.imag, cval=cval, **kwargs)
513
+ return output
514
+
515
+
516
+ def _expand_origin(ndim_image, axes, origin):
517
+ num_axes = len(axes)
518
+ origins = _ni_support._normalize_sequence(origin, num_axes)
519
+ if num_axes < ndim_image:
520
+ # set origin = 0 for any axes not being filtered
521
+ origins_temp = [0,] * ndim_image
522
+ for o, ax in zip(origins, axes):
523
+ origins_temp[ax] = o
524
+ origins = origins_temp
525
+ return origins
526
+
527
+
528
+ def _expand_footprint(ndim_image, axes, footprint,
529
+ footprint_name="footprint"):
530
+ num_axes = len(axes)
531
+ if num_axes < ndim_image:
532
+ if footprint.ndim != num_axes:
533
+ raise RuntimeError(f"{footprint_name}.ndim ({footprint.ndim}) "
534
+ f"must match len(axes) ({num_axes})")
535
+
536
+ footprint = np.expand_dims(
537
+ footprint,
538
+ tuple(ax for ax in range(ndim_image) if ax not in axes)
539
+ )
540
+ return footprint
541
+
542
+
543
+ def _expand_mode(ndim_image, axes, mode):
544
+ num_axes = len(axes)
545
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
546
+ # set mode = 'constant' for any axes not being filtered
547
+ modes = _ni_support._normalize_sequence(mode, num_axes)
548
+ modes_temp = ['constant'] * ndim_image
549
+ for m, ax in zip(modes, axes):
550
+ modes_temp[ax] = m
551
+ mode = modes_temp
552
+ return mode
553
+
554
+
555
+ @_ni_docstrings.docfiller
556
+ def correlate1d(input, weights, axis=-1, output=None, mode="reflect",
557
+ cval=0.0, origin=0):
558
+ """Calculate a 1-D correlation along the given axis.
559
+
560
+ The lines of the array along the given axis are correlated with the
561
+ given weights.
562
+
563
+ Parameters
564
+ ----------
565
+ %(input)s
566
+ weights : array
567
+ 1-D sequence of numbers.
568
+ %(axis)s
569
+ %(output)s
570
+ %(mode_reflect)s
571
+ %(cval)s
572
+ %(origin)s
573
+
574
+ Returns
575
+ -------
576
+ result : ndarray
577
+ Correlation result. Has the same shape as `input`.
578
+
579
+ Examples
580
+ --------
581
+ >>> from scipy.ndimage import correlate1d
582
+ >>> correlate1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3])
583
+ array([ 8, 26, 8, 12, 7, 28, 36, 9])
584
+ """
585
+ input = np.asarray(input)
586
+ weights = np.asarray(weights)
587
+ complex_input = input.dtype.kind == 'c'
588
+ complex_weights = weights.dtype.kind == 'c'
589
+ if complex_input or complex_weights:
590
+ if complex_weights:
591
+ weights = weights.conj()
592
+ weights = weights.astype(np.complex128, copy=False)
593
+ kwargs = dict(axis=axis, mode=mode, origin=origin)
594
+ output = _ni_support._get_output(output, input, complex_output=True)
595
+ return _complex_via_real_components(correlate1d, input, weights,
596
+ output, cval, **kwargs)
597
+
598
+ output = _ni_support._get_output(output, input)
599
+ weights = np.asarray(weights, dtype=np.float64)
600
+ if weights.ndim != 1 or weights.shape[0] < 1:
601
+ raise RuntimeError('no filter weights given')
602
+ if not weights.flags.contiguous:
603
+ weights = weights.copy()
604
+ axis = normalize_axis_index(axis, input.ndim)
605
+ if _invalid_origin(origin, len(weights)):
606
+ raise ValueError('Invalid origin; origin must satisfy '
607
+ '-(len(weights) // 2) <= origin <= '
608
+ '(len(weights)-1) // 2')
609
+ mode = _ni_support._extend_mode_to_code(mode)
610
+ _nd_image.correlate1d(input, weights, axis, output, mode, cval,
611
+ origin)
612
+ return output
613
+
614
+
615
+ @_ni_docstrings.docfiller
616
+ def convolve1d(input, weights, axis=-1, output=None, mode="reflect",
617
+ cval=0.0, origin=0):
618
+ """Calculate a 1-D convolution along the given axis.
619
+
620
+ The lines of the array along the given axis are convolved with the
621
+ given weights.
622
+
623
+ Parameters
624
+ ----------
625
+ %(input)s
626
+ weights : ndarray
627
+ 1-D sequence of numbers.
628
+ %(axis)s
629
+ %(output)s
630
+ %(mode_reflect)s
631
+ %(cval)s
632
+ %(origin)s
633
+
634
+ Returns
635
+ -------
636
+ convolve1d : ndarray
637
+ Convolved array with same shape as input
638
+
639
+ Examples
640
+ --------
641
+ >>> from scipy.ndimage import convolve1d
642
+ >>> convolve1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3])
643
+ array([14, 24, 4, 13, 12, 36, 27, 0])
644
+ """
645
+ weights = np.asarray(weights)
646
+ weights = weights[::-1]
647
+ origin = -origin
648
+ if not weights.shape[0] & 1:
649
+ origin -= 1
650
+ if weights.dtype.kind == 'c':
651
+ # pre-conjugate here to counteract the conjugation in correlate1d
652
+ weights = weights.conj()
653
+ return correlate1d(input, weights, axis, output, mode, cval, origin)
654
+
655
+
656
+ def _gaussian_kernel1d(sigma, order, radius):
657
+ """
658
+ Computes a 1-D Gaussian convolution kernel.
659
+ """
660
+ if order < 0:
661
+ raise ValueError('order must be non-negative')
662
+ exponent_range = np.arange(order + 1)
663
+ sigma2 = sigma * sigma
664
+ x = np.arange(-radius, radius+1)
665
+ phi_x = np.exp(-0.5 / sigma2 * x ** 2)
666
+ phi_x = phi_x / phi_x.sum()
667
+
668
+ if order == 0:
669
+ return phi_x
670
+ else:
671
+ # f(x) = q(x) * phi(x) = q(x) * exp(p(x))
672
+ # f'(x) = (q'(x) + q(x) * p'(x)) * phi(x)
673
+ # p'(x) = -1 / sigma ** 2
674
+ # Implement q'(x) + q(x) * p'(x) as a matrix operator and apply to the
675
+ # coefficients of q(x)
676
+ q = np.zeros(order + 1)
677
+ q[0] = 1
678
+ D = np.diag(exponent_range[1:], 1) # D @ q(x) = q'(x)
679
+ P = np.diag(np.ones(order)/-sigma2, -1) # P @ q(x) = q(x) * p'(x)
680
+ Q_deriv = D + P
681
+ for _ in range(order):
682
+ q = Q_deriv.dot(q)
683
+ q = (x[:, None] ** exponent_range).dot(q)
684
+ return q * phi_x
685
+
686
+
687
+ @_ni_docstrings.docfiller
688
+ def gaussian_filter1d(input, sigma, axis=-1, order=0, output=None,
689
+ mode="reflect", cval=0.0, truncate=4.0, *, radius=None):
690
+ """1-D Gaussian filter.
691
+
692
+ Parameters
693
+ ----------
694
+ %(input)s
695
+ sigma : scalar
696
+ standard deviation for Gaussian kernel
697
+ %(axis)s
698
+ order : int, optional
699
+ An order of 0 corresponds to convolution with a Gaussian
700
+ kernel. A positive order corresponds to convolution with
701
+ that derivative of a Gaussian.
702
+ %(output)s
703
+ %(mode_reflect)s
704
+ %(cval)s
705
+ truncate : float, optional
706
+ Truncate the filter at this many standard deviations.
707
+ Default is 4.0.
708
+ radius : None or int, optional
709
+ Radius of the Gaussian kernel. If specified, the size of
710
+ the kernel will be ``2*radius + 1``, and `truncate` is ignored.
711
+ Default is None.
712
+
713
+ Returns
714
+ -------
715
+ gaussian_filter1d : ndarray
716
+
717
+ Notes
718
+ -----
719
+ The Gaussian kernel will have size ``2*radius + 1`` along each axis. If
720
+ `radius` is None, a default ``radius = round(truncate * sigma)`` will be
721
+ used.
722
+
723
+ Examples
724
+ --------
725
+ >>> from scipy.ndimage import gaussian_filter1d
726
+ >>> import numpy as np
727
+ >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 1)
728
+ array([ 1.42704095, 2.06782203, 3. , 3.93217797, 4.57295905])
729
+ >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 4)
730
+ array([ 2.91948343, 2.95023502, 3. , 3.04976498, 3.08051657])
731
+ >>> import matplotlib.pyplot as plt
732
+ >>> rng = np.random.default_rng()
733
+ >>> x = rng.standard_normal(101).cumsum()
734
+ >>> y3 = gaussian_filter1d(x, 3)
735
+ >>> y6 = gaussian_filter1d(x, 6)
736
+ >>> plt.plot(x, 'k', label='original data')
737
+ >>> plt.plot(y3, '--', label='filtered, sigma=3')
738
+ >>> plt.plot(y6, ':', label='filtered, sigma=6')
739
+ >>> plt.legend()
740
+ >>> plt.grid()
741
+ >>> plt.show()
742
+
743
+ """
744
+ sd = float(sigma)
745
+ # make the radius of the filter equal to truncate standard deviations
746
+ lw = int(truncate * sd + 0.5)
747
+ if radius is not None:
748
+ lw = radius
749
+ if not isinstance(lw, numbers.Integral) or lw < 0:
750
+ raise ValueError('Radius must be a nonnegative integer.')
751
+ # Since we are calling correlate, not convolve, revert the kernel
752
+ weights = _gaussian_kernel1d(sigma, order, lw)[::-1]
753
+ return correlate1d(input, weights, axis, output, mode, cval, 0)
754
+
755
+
756
+ @_ni_docstrings.docfiller
757
+ def gaussian_filter(input, sigma, order=0, output=None,
758
+ mode="reflect", cval=0.0, truncate=4.0, *, radius=None,
759
+ axes=None):
760
+ """Multidimensional Gaussian filter.
761
+
762
+ Parameters
763
+ ----------
764
+ %(input)s
765
+ sigma : scalar or sequence of scalars
766
+ Standard deviation for Gaussian kernel. The standard
767
+ deviations of the Gaussian filter are given for each axis as a
768
+ sequence, or as a single number, in which case it is equal for
769
+ all axes.
770
+ order : int or sequence of ints, optional
771
+ The order of the filter along each axis is given as a sequence
772
+ of integers, or as a single number. An order of 0 corresponds
773
+ to convolution with a Gaussian kernel. A positive order
774
+ corresponds to convolution with that derivative of a Gaussian.
775
+ %(output)s
776
+ %(mode_multiple)s
777
+ %(cval)s
778
+ truncate : float, optional
779
+ Truncate the filter at this many standard deviations.
780
+ Default is 4.0.
781
+ radius : None or int or sequence of ints, optional
782
+ Radius of the Gaussian kernel. The radius are given for each axis
783
+ as a sequence, or as a single number, in which case it is equal
784
+ for all axes. If specified, the size of the kernel along each axis
785
+ will be ``2*radius + 1``, and `truncate` is ignored.
786
+ Default is None.
787
+ axes : tuple of int or None, optional
788
+ If None, `input` is filtered along all axes. Otherwise,
789
+ `input` is filtered along the specified axes. When `axes` is
790
+ specified, any tuples used for `sigma`, `order`, `mode` and/or `radius`
791
+ must match the length of `axes`. The ith entry in any of these tuples
792
+ corresponds to the ith entry in `axes`.
793
+
794
+ Returns
795
+ -------
796
+ gaussian_filter : ndarray
797
+ Returned array of same shape as `input`.
798
+
799
+ Notes
800
+ -----
801
+ The multidimensional filter is implemented as a sequence of
802
+ 1-D convolution filters. The intermediate arrays are
803
+ stored in the same data type as the output. Therefore, for output
804
+ types with a limited precision, the results may be imprecise
805
+ because intermediate results may be stored with insufficient
806
+ precision.
807
+
808
+ The Gaussian kernel will have size ``2*radius + 1`` along each axis. If
809
+ `radius` is None, the default ``radius = round(truncate * sigma)`` will be
810
+ used.
811
+
812
+ Examples
813
+ --------
814
+ >>> from scipy.ndimage import gaussian_filter
815
+ >>> import numpy as np
816
+ >>> a = np.arange(50, step=2).reshape((5,5))
817
+ >>> a
818
+ array([[ 0, 2, 4, 6, 8],
819
+ [10, 12, 14, 16, 18],
820
+ [20, 22, 24, 26, 28],
821
+ [30, 32, 34, 36, 38],
822
+ [40, 42, 44, 46, 48]])
823
+ >>> gaussian_filter(a, sigma=1)
824
+ array([[ 4, 6, 8, 9, 11],
825
+ [10, 12, 14, 15, 17],
826
+ [20, 22, 24, 25, 27],
827
+ [29, 31, 33, 34, 36],
828
+ [35, 37, 39, 40, 42]])
829
+
830
+ >>> from scipy import datasets
831
+ >>> import matplotlib.pyplot as plt
832
+ >>> fig = plt.figure()
833
+ >>> plt.gray() # show the filtered result in grayscale
834
+ >>> ax1 = fig.add_subplot(121) # left side
835
+ >>> ax2 = fig.add_subplot(122) # right side
836
+ >>> ascent = datasets.ascent()
837
+ >>> result = gaussian_filter(ascent, sigma=5)
838
+ >>> ax1.imshow(ascent)
839
+ >>> ax2.imshow(result)
840
+ >>> plt.show()
841
+ """
842
+ input = np.asarray(input)
843
+ output = _ni_support._get_output(output, input)
844
+
845
+ axes = _ni_support._check_axes(axes, input.ndim)
846
+ num_axes = len(axes)
847
+ orders = _ni_support._normalize_sequence(order, num_axes)
848
+ sigmas = _ni_support._normalize_sequence(sigma, num_axes)
849
+ modes = _ni_support._normalize_sequence(mode, num_axes)
850
+ radiuses = _ni_support._normalize_sequence(radius, num_axes)
851
+ axes = [(axes[ii], sigmas[ii], orders[ii], modes[ii], radiuses[ii])
852
+ for ii in range(num_axes) if sigmas[ii] > 1e-15]
853
+ if len(axes) > 0:
854
+ for axis, sigma, order, mode, radius in axes:
855
+ gaussian_filter1d(input, sigma, axis, order, output,
856
+ mode, cval, truncate, radius=radius)
857
+ input = output
858
+ else:
859
+ output[...] = input[...]
860
+ return output
861
+
862
+
863
+ @_ni_docstrings.docfiller
864
+ def prewitt(input, axis=-1, output=None, mode="reflect", cval=0.0):
865
+ """Calculate a Prewitt filter.
866
+
867
+ Parameters
868
+ ----------
869
+ %(input)s
870
+ %(axis)s
871
+ %(output)s
872
+ %(mode_multiple)s
873
+ %(cval)s
874
+
875
+ Returns
876
+ -------
877
+ prewitt : ndarray
878
+ Filtered array. Has the same shape as `input`.
879
+
880
+ See Also
881
+ --------
882
+ sobel: Sobel filter
883
+
884
+ Notes
885
+ -----
886
+ This function computes the one-dimensional Prewitt filter.
887
+ Horizontal edges are emphasised with the horizontal transform (axis=0),
888
+ vertical edges with the vertical transform (axis=1), and so on for higher
889
+ dimensions. These can be combined to give the magnitude.
890
+
891
+ Examples
892
+ --------
893
+ >>> from scipy import ndimage, datasets
894
+ >>> import matplotlib.pyplot as plt
895
+ >>> import numpy as np
896
+ >>> ascent = datasets.ascent()
897
+ >>> prewitt_h = ndimage.prewitt(ascent, axis=0)
898
+ >>> prewitt_v = ndimage.prewitt(ascent, axis=1)
899
+ >>> magnitude = np.sqrt(prewitt_h ** 2 + prewitt_v ** 2)
900
+ >>> magnitude *= 255 / np.max(magnitude) # Normalization
901
+ >>> fig, axes = plt.subplots(2, 2, figsize = (8, 8))
902
+ >>> plt.gray()
903
+ >>> axes[0, 0].imshow(ascent)
904
+ >>> axes[0, 1].imshow(prewitt_h)
905
+ >>> axes[1, 0].imshow(prewitt_v)
906
+ >>> axes[1, 1].imshow(magnitude)
907
+ >>> titles = ["original", "horizontal", "vertical", "magnitude"]
908
+ >>> for i, ax in enumerate(axes.ravel()):
909
+ ... ax.set_title(titles[i])
910
+ ... ax.axis("off")
911
+ >>> plt.show()
912
+
913
+ """
914
+ input = np.asarray(input)
915
+ axis = normalize_axis_index(axis, input.ndim)
916
+ output = _ni_support._get_output(output, input)
917
+ modes = _ni_support._normalize_sequence(mode, input.ndim)
918
+ correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0)
919
+ axes = [ii for ii in range(input.ndim) if ii != axis]
920
+ for ii in axes:
921
+ correlate1d(output, [1, 1, 1], ii, output, modes[ii], cval, 0,)
922
+ return output
923
+
924
+
925
+ @_ni_docstrings.docfiller
926
+ def sobel(input, axis=-1, output=None, mode="reflect", cval=0.0):
927
+ """Calculate a Sobel filter.
928
+
929
+ Parameters
930
+ ----------
931
+ %(input)s
932
+ %(axis)s
933
+ %(output)s
934
+ %(mode_multiple)s
935
+ %(cval)s
936
+
937
+ Returns
938
+ -------
939
+ sobel : ndarray
940
+ Filtered array. Has the same shape as `input`.
941
+
942
+ Notes
943
+ -----
944
+ This function computes the axis-specific Sobel gradient.
945
+ The horizontal edges can be emphasised with the horizontal transform (axis=0),
946
+ the vertical edges with the vertical transform (axis=1) and so on for higher
947
+ dimensions. These can be combined to give the magnitude.
948
+
949
+ Examples
950
+ --------
951
+ >>> from scipy import ndimage, datasets
952
+ >>> import matplotlib.pyplot as plt
953
+ >>> import numpy as np
954
+ >>> ascent = datasets.ascent().astype('int32')
955
+ >>> sobel_h = ndimage.sobel(ascent, 0) # horizontal gradient
956
+ >>> sobel_v = ndimage.sobel(ascent, 1) # vertical gradient
957
+ >>> magnitude = np.sqrt(sobel_h**2 + sobel_v**2)
958
+ >>> magnitude *= 255.0 / np.max(magnitude) # normalization
959
+ >>> fig, axs = plt.subplots(2, 2, figsize=(8, 8))
960
+ >>> plt.gray() # show the filtered result in grayscale
961
+ >>> axs[0, 0].imshow(ascent)
962
+ >>> axs[0, 1].imshow(sobel_h)
963
+ >>> axs[1, 0].imshow(sobel_v)
964
+ >>> axs[1, 1].imshow(magnitude)
965
+ >>> titles = ["original", "horizontal", "vertical", "magnitude"]
966
+ >>> for i, ax in enumerate(axs.ravel()):
967
+ ... ax.set_title(titles[i])
968
+ ... ax.axis("off")
969
+ >>> plt.show()
970
+
971
+ """
972
+ input = np.asarray(input)
973
+ axis = normalize_axis_index(axis, input.ndim)
974
+ output = _ni_support._get_output(output, input)
975
+ modes = _ni_support._normalize_sequence(mode, input.ndim)
976
+ correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0)
977
+ axes = [ii for ii in range(input.ndim) if ii != axis]
978
+ for ii in axes:
979
+ correlate1d(output, [1, 2, 1], ii, output, modes[ii], cval, 0)
980
+ return output
981
+
982
+
983
+ @_ni_docstrings.docfiller
984
+ def generic_laplace(input, derivative2, output=None, mode="reflect",
985
+ cval=0.0,
986
+ extra_arguments=(),
987
+ extra_keywords=None,
988
+ *, axes=None):
989
+ """
990
+ N-D Laplace filter using a provided second derivative function.
991
+
992
+ Parameters
993
+ ----------
994
+ %(input)s
995
+ derivative2 : callable
996
+ Callable with the following signature::
997
+
998
+ derivative2(input, axis, output, mode, cval,
999
+ *extra_arguments, **extra_keywords)
1000
+
1001
+ See `extra_arguments`, `extra_keywords` below.
1002
+ %(output)s
1003
+ %(mode_multiple)s
1004
+ %(cval)s
1005
+ %(extra_keywords)s
1006
+ %(extra_arguments)s
1007
+ axes : tuple of int or None
1008
+ The axes over which to apply the filter. If a `mode` tuple is
1009
+ provided, its length must match the number of axes.
1010
+
1011
+ Returns
1012
+ -------
1013
+ generic_laplace : ndarray
1014
+ Filtered array. Has the same shape as `input`.
1015
+
1016
+ """
1017
+ if extra_keywords is None:
1018
+ extra_keywords = {}
1019
+ input = np.asarray(input)
1020
+ output = _ni_support._get_output(output, input)
1021
+ axes = _ni_support._check_axes(axes, input.ndim)
1022
+ if len(axes) > 0:
1023
+ modes = _ni_support._normalize_sequence(mode, len(axes))
1024
+ derivative2(input, axes[0], output, modes[0], cval,
1025
+ *extra_arguments, **extra_keywords)
1026
+ for ii in range(1, len(axes)):
1027
+ tmp = derivative2(input, axes[ii], output.dtype, modes[ii], cval,
1028
+ *extra_arguments, **extra_keywords)
1029
+ output += tmp
1030
+ else:
1031
+ output[...] = input[...]
1032
+ return output
1033
+
1034
+
1035
+ @_ni_docstrings.docfiller
1036
+ def laplace(input, output=None, mode="reflect", cval=0.0, *, axes=None):
1037
+ """N-D Laplace filter based on approximate second derivatives.
1038
+
1039
+ Parameters
1040
+ ----------
1041
+ %(input)s
1042
+ %(output)s
1043
+ %(mode_multiple)s
1044
+ %(cval)s
1045
+ axes : tuple of int or None
1046
+ The axes over which to apply the filter. If a `mode` tuple is
1047
+ provided, its length must match the number of axes.
1048
+
1049
+ Returns
1050
+ -------
1051
+ laplace : ndarray
1052
+ Filtered array. Has the same shape as `input`.
1053
+
1054
+ Examples
1055
+ --------
1056
+ >>> from scipy import ndimage, datasets
1057
+ >>> import matplotlib.pyplot as plt
1058
+ >>> fig = plt.figure()
1059
+ >>> plt.gray() # show the filtered result in grayscale
1060
+ >>> ax1 = fig.add_subplot(121) # left side
1061
+ >>> ax2 = fig.add_subplot(122) # right side
1062
+ >>> ascent = datasets.ascent()
1063
+ >>> result = ndimage.laplace(ascent)
1064
+ >>> ax1.imshow(ascent)
1065
+ >>> ax2.imshow(result)
1066
+ >>> plt.show()
1067
+ """
1068
+ def derivative2(input, axis, output, mode, cval):
1069
+ return correlate1d(input, [1, -2, 1], axis, output, mode, cval, 0)
1070
+ return generic_laplace(input, derivative2, output, mode, cval, axes=axes)
1071
+
1072
+
1073
+ @_ni_docstrings.docfiller
1074
+ def gaussian_laplace(input, sigma, output=None, mode="reflect",
1075
+ cval=0.0, *, axes=None, **kwargs):
1076
+ """Multidimensional Laplace filter using Gaussian second derivatives.
1077
+
1078
+ Parameters
1079
+ ----------
1080
+ %(input)s
1081
+ sigma : scalar or sequence of scalars
1082
+ The standard deviations of the Gaussian filter are given for
1083
+ each axis as a sequence, or as a single number, in which case
1084
+ it is equal for all axes.
1085
+ %(output)s
1086
+ %(mode_multiple)s
1087
+ %(cval)s
1088
+ axes : tuple of int or None
1089
+ The axes over which to apply the filter. If `sigma` or `mode` tuples
1090
+ are provided, their length must match the number of axes.
1091
+ Extra keyword arguments will be passed to gaussian_filter().
1092
+
1093
+ Returns
1094
+ -------
1095
+ gaussian_laplace : ndarray
1096
+ Filtered array. Has the same shape as `input`.
1097
+
1098
+ Examples
1099
+ --------
1100
+ >>> from scipy import ndimage, datasets
1101
+ >>> import matplotlib.pyplot as plt
1102
+ >>> ascent = datasets.ascent()
1103
+
1104
+ >>> fig = plt.figure()
1105
+ >>> plt.gray() # show the filtered result in grayscale
1106
+ >>> ax1 = fig.add_subplot(121) # left side
1107
+ >>> ax2 = fig.add_subplot(122) # right side
1108
+
1109
+ >>> result = ndimage.gaussian_laplace(ascent, sigma=1)
1110
+ >>> ax1.imshow(result)
1111
+
1112
+ >>> result = ndimage.gaussian_laplace(ascent, sigma=3)
1113
+ >>> ax2.imshow(result)
1114
+ >>> plt.show()
1115
+ """
1116
+ input = np.asarray(input)
1117
+
1118
+ def derivative2(input, axis, output, mode, cval, sigma, **kwargs):
1119
+ order = [0] * input.ndim
1120
+ order[axis] = 2
1121
+ return gaussian_filter(input, sigma, order, output, mode, cval,
1122
+ **kwargs)
1123
+
1124
+ axes = _ni_support._check_axes(axes, input.ndim)
1125
+ num_axes = len(axes)
1126
+ sigma = _ni_support._normalize_sequence(sigma, num_axes)
1127
+ if num_axes < input.ndim:
1128
+ # set sigma = 0 for any axes not being filtered
1129
+ sigma_temp = [0,] * input.ndim
1130
+ for s, ax in zip(sigma, axes):
1131
+ sigma_temp[ax] = s
1132
+ sigma = sigma_temp
1133
+
1134
+ return generic_laplace(input, derivative2, output, mode, cval,
1135
+ extra_arguments=(sigma,),
1136
+ extra_keywords=kwargs,
1137
+ axes=axes)
1138
+
1139
+
1140
+ @_ni_docstrings.docfiller
1141
+ def generic_gradient_magnitude(input, derivative, output=None,
1142
+ mode="reflect", cval=0.0,
1143
+ extra_arguments=(), extra_keywords=None,
1144
+ *, axes=None):
1145
+ """Gradient magnitude using a provided gradient function.
1146
+
1147
+ Parameters
1148
+ ----------
1149
+ %(input)s
1150
+ derivative : callable
1151
+ Callable with the following signature::
1152
+
1153
+ derivative(input, axis, output, mode, cval,
1154
+ *extra_arguments, **extra_keywords)
1155
+
1156
+ See `extra_arguments`, `extra_keywords` below.
1157
+ `derivative` can assume that `input` and `output` are ndarrays.
1158
+ Note that the output from `derivative` is modified inplace;
1159
+ be careful to copy important inputs before returning them.
1160
+ %(output)s
1161
+ %(mode_multiple)s
1162
+ %(cval)s
1163
+ %(extra_keywords)s
1164
+ %(extra_arguments)s
1165
+ axes : tuple of int or None
1166
+ The axes over which to apply the filter. If a `mode` tuple is
1167
+ provided, its length must match the number of axes.
1168
+
1169
+ Returns
1170
+ -------
1171
+ generic_gradient_magnitude : ndarray
1172
+ Filtered array. Has the same shape as `input`.
1173
+
1174
+ """
1175
+ if extra_keywords is None:
1176
+ extra_keywords = {}
1177
+ input = np.asarray(input)
1178
+ output = _ni_support._get_output(output, input)
1179
+ axes = _ni_support._check_axes(axes, input.ndim)
1180
+ if len(axes) > 0:
1181
+ modes = _ni_support._normalize_sequence(mode, len(axes))
1182
+ derivative(input, axes[0], output, modes[0], cval,
1183
+ *extra_arguments, **extra_keywords)
1184
+ np.multiply(output, output, output)
1185
+ for ii in range(1, len(axes)):
1186
+ tmp = derivative(input, axes[ii], output.dtype, modes[ii], cval,
1187
+ *extra_arguments, **extra_keywords)
1188
+ np.multiply(tmp, tmp, tmp)
1189
+ output += tmp
1190
+ # This allows the sqrt to work with a different default casting
1191
+ np.sqrt(output, output, casting='unsafe')
1192
+ else:
1193
+ output[...] = input[...]
1194
+ return output
1195
+
1196
+
1197
+ @_ni_docstrings.docfiller
1198
+ def gaussian_gradient_magnitude(input, sigma, output=None,
1199
+ mode="reflect", cval=0.0, *, axes=None,
1200
+ **kwargs):
1201
+ """Multidimensional gradient magnitude using Gaussian derivatives.
1202
+
1203
+ Parameters
1204
+ ----------
1205
+ %(input)s
1206
+ sigma : scalar or sequence of scalars
1207
+ The standard deviations of the Gaussian filter are given for
1208
+ each axis as a sequence, or as a single number, in which case
1209
+ it is equal for all axes.
1210
+ %(output)s
1211
+ %(mode_multiple)s
1212
+ %(cval)s
1213
+ axes : tuple of int or None
1214
+ The axes over which to apply the filter. If `sigma` or `mode` tuples
1215
+ are provided, their length must match the number of axes.
1216
+ Extra keyword arguments will be passed to gaussian_filter().
1217
+
1218
+ Returns
1219
+ -------
1220
+ gaussian_gradient_magnitude : ndarray
1221
+ Filtered array. Has the same shape as `input`.
1222
+
1223
+ Examples
1224
+ --------
1225
+ >>> from scipy import ndimage, datasets
1226
+ >>> import matplotlib.pyplot as plt
1227
+ >>> fig = plt.figure()
1228
+ >>> plt.gray() # show the filtered result in grayscale
1229
+ >>> ax1 = fig.add_subplot(121) # left side
1230
+ >>> ax2 = fig.add_subplot(122) # right side
1231
+ >>> ascent = datasets.ascent()
1232
+ >>> result = ndimage.gaussian_gradient_magnitude(ascent, sigma=5)
1233
+ >>> ax1.imshow(ascent)
1234
+ >>> ax2.imshow(result)
1235
+ >>> plt.show()
1236
+ """
1237
+ input = np.asarray(input)
1238
+
1239
+ def derivative(input, axis, output, mode, cval, sigma, **kwargs):
1240
+ order = [0] * input.ndim
1241
+ order[axis] = 1
1242
+ return gaussian_filter(input, sigma, order, output, mode,
1243
+ cval, **kwargs)
1244
+
1245
+ return generic_gradient_magnitude(input, derivative, output, mode,
1246
+ cval, extra_arguments=(sigma,),
1247
+ extra_keywords=kwargs, axes=axes)
1248
+
1249
+
1250
+ def _correlate_or_convolve(input, weights, output, mode, cval, origin,
1251
+ convolution, axes):
1252
+ input = np.asarray(input)
1253
+ weights = np.asarray(weights)
1254
+ complex_input = input.dtype.kind == 'c'
1255
+ complex_weights = weights.dtype.kind == 'c'
1256
+ if complex_input or complex_weights:
1257
+ if complex_weights and not convolution:
1258
+ # As for np.correlate, conjugate weights rather than input.
1259
+ weights = weights.conj()
1260
+ kwargs = dict(
1261
+ mode=mode, origin=origin, convolution=convolution, axes=axes
1262
+ )
1263
+ output = _ni_support._get_output(output, input, complex_output=True)
1264
+
1265
+ return _complex_via_real_components(_correlate_or_convolve, input,
1266
+ weights, output, cval, **kwargs)
1267
+
1268
+ axes = _ni_support._check_axes(axes, input.ndim)
1269
+ weights = np.asarray(weights, dtype=np.float64)
1270
+
1271
+ # expand weights and origins if num_axes < input.ndim
1272
+ weights = _expand_footprint(input.ndim, axes, weights, "weights")
1273
+ origins = _expand_origin(input.ndim, axes, origin)
1274
+
1275
+ wshape = [ii for ii in weights.shape if ii > 0]
1276
+ if len(wshape) != input.ndim:
1277
+ raise RuntimeError(f"weights.ndim ({len(wshape)}) must match "
1278
+ f"len(axes) ({len(axes)})")
1279
+ if convolution:
1280
+ weights = weights[tuple([slice(None, None, -1)] * weights.ndim)]
1281
+ for ii in range(len(origins)):
1282
+ origins[ii] = -origins[ii]
1283
+ if not weights.shape[ii] & 1:
1284
+ origins[ii] -= 1
1285
+ for origin, lenw in zip(origins, wshape):
1286
+ if _invalid_origin(origin, lenw):
1287
+ raise ValueError('Invalid origin; origin must satisfy '
1288
+ '-(weights.shape[k] // 2) <= origin[k] <= '
1289
+ '(weights.shape[k]-1) // 2')
1290
+
1291
+ if not weights.flags.contiguous:
1292
+ weights = weights.copy()
1293
+ output = _ni_support._get_output(output, input)
1294
+ temp_needed = np.may_share_memory(input, output)
1295
+ if temp_needed:
1296
+ # input and output arrays cannot share memory
1297
+ temp = output
1298
+ output = _ni_support._get_output(output.dtype, input)
1299
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
1300
+ raise RuntimeError("A sequence of modes is not supported")
1301
+ mode = _ni_support._extend_mode_to_code(mode)
1302
+ _nd_image.correlate(input, weights, output, mode, cval, origins)
1303
+ if temp_needed:
1304
+ temp[...] = output
1305
+ output = temp
1306
+ return output
1307
+
1308
+
1309
+ @_ni_docstrings.docfiller
1310
+ def correlate(input, weights, output=None, mode='reflect', cval=0.0,
1311
+ origin=0, *, axes=None):
1312
+ """
1313
+ Multidimensional correlation.
1314
+
1315
+ The array is correlated with the given kernel.
1316
+
1317
+ Parameters
1318
+ ----------
1319
+ %(input)s
1320
+ weights : ndarray
1321
+ array of weights, same number of dimensions as input
1322
+ %(output)s
1323
+ %(mode_reflect)s
1324
+ %(cval)s
1325
+ %(origin_multiple)s
1326
+ axes : tuple of int or None, optional
1327
+ If None, `input` is filtered along all axes. Otherwise,
1328
+ `input` is filtered along the specified axes. When `axes` is
1329
+ specified, any tuples used for `mode` or `origin` must match the length
1330
+ of `axes`. The ith entry in any of these tuples corresponds to the ith
1331
+ entry in `axes`.
1332
+
1333
+ Returns
1334
+ -------
1335
+ result : ndarray
1336
+ The result of correlation of `input` with `weights`.
1337
+
1338
+ See Also
1339
+ --------
1340
+ convolve : Convolve an image with a kernel.
1341
+
1342
+ Examples
1343
+ --------
1344
+ Correlation is the process of moving a filter mask often referred to
1345
+ as kernel over the image and computing the sum of products at each location.
1346
+
1347
+ >>> from scipy.ndimage import correlate
1348
+ >>> import numpy as np
1349
+ >>> input_img = np.arange(25).reshape(5,5)
1350
+ >>> print(input_img)
1351
+ [[ 0 1 2 3 4]
1352
+ [ 5 6 7 8 9]
1353
+ [10 11 12 13 14]
1354
+ [15 16 17 18 19]
1355
+ [20 21 22 23 24]]
1356
+
1357
+ Define a kernel (weights) for correlation. In this example, it is for sum of
1358
+ center and up, down, left and right next elements.
1359
+
1360
+ >>> weights = [[0, 1, 0],
1361
+ ... [1, 1, 1],
1362
+ ... [0, 1, 0]]
1363
+
1364
+ We can calculate a correlation result:
1365
+ For example, element ``[2,2]`` is ``7 + 11 + 12 + 13 + 17 = 60``.
1366
+
1367
+ >>> correlate(input_img, weights)
1368
+ array([[ 6, 10, 15, 20, 24],
1369
+ [ 26, 30, 35, 40, 44],
1370
+ [ 51, 55, 60, 65, 69],
1371
+ [ 76, 80, 85, 90, 94],
1372
+ [ 96, 100, 105, 110, 114]])
1373
+
1374
+ """
1375
+ return _correlate_or_convolve(input, weights, output, mode, cval,
1376
+ origin, False, axes)
1377
+
1378
+
1379
+ @_ni_docstrings.docfiller
1380
+ def convolve(input, weights, output=None, mode='reflect', cval=0.0,
1381
+ origin=0, *, axes=None):
1382
+ """
1383
+ Multidimensional convolution.
1384
+
1385
+ The array is convolved with the given kernel.
1386
+
1387
+ Parameters
1388
+ ----------
1389
+ %(input)s
1390
+ weights : array_like
1391
+ Array of weights, same number of dimensions as input
1392
+ %(output)s
1393
+ %(mode_reflect)s
1394
+ cval : scalar, optional
1395
+ Value to fill past edges of input if `mode` is 'constant'. Default
1396
+ is 0.0
1397
+ origin : int or sequence, optional
1398
+ Controls the placement of the filter on the input array's pixels.
1399
+ A value of 0 (the default) centers the filter over the pixel, with
1400
+ positive values shifting the filter to the right, and negative ones
1401
+ to the left. By passing a sequence of origins with length equal to
1402
+ the number of dimensions of the input array, different shifts can
1403
+ be specified along each axis.
1404
+ axes : tuple of int or None, optional
1405
+ If None, `input` is filtered along all axes. Otherwise,
1406
+ `input` is filtered along the specified axes. When `axes` is
1407
+ specified, any tuples used for `mode` or `origin` must match the length
1408
+ of `axes`. The ith entry in any of these tuples corresponds to the ith
1409
+ entry in `axes`.
1410
+
1411
+ Returns
1412
+ -------
1413
+ result : ndarray
1414
+ The result of convolution of `input` with `weights`.
1415
+
1416
+ See Also
1417
+ --------
1418
+ correlate : Correlate an image with a kernel.
1419
+
1420
+ Notes
1421
+ -----
1422
+ Each value in result is :math:`C_i = \\sum_j{I_{i+k-j} W_j}`, where
1423
+ W is the `weights` kernel,
1424
+ j is the N-D spatial index over :math:`W`,
1425
+ I is the `input` and k is the coordinate of the center of
1426
+ W, specified by `origin` in the input parameters.
1427
+
1428
+ Examples
1429
+ --------
1430
+ Perhaps the simplest case to understand is ``mode='constant', cval=0.0``,
1431
+ because in this case borders (i.e., where the `weights` kernel, centered
1432
+ on any one value, extends beyond an edge of `input`) are treated as zeros.
1433
+
1434
+ >>> import numpy as np
1435
+ >>> a = np.array([[1, 2, 0, 0],
1436
+ ... [5, 3, 0, 4],
1437
+ ... [0, 0, 0, 7],
1438
+ ... [9, 3, 0, 0]])
1439
+ >>> k = np.array([[1,1,1],[1,1,0],[1,0,0]])
1440
+ >>> from scipy import ndimage
1441
+ >>> ndimage.convolve(a, k, mode='constant', cval=0.0)
1442
+ array([[11, 10, 7, 4],
1443
+ [10, 3, 11, 11],
1444
+ [15, 12, 14, 7],
1445
+ [12, 3, 7, 0]])
1446
+
1447
+ Setting ``cval=1.0`` is equivalent to padding the outer edge of `input`
1448
+ with 1.0's (and then extracting only the original region of the result).
1449
+
1450
+ >>> ndimage.convolve(a, k, mode='constant', cval=1.0)
1451
+ array([[13, 11, 8, 7],
1452
+ [11, 3, 11, 14],
1453
+ [16, 12, 14, 10],
1454
+ [15, 6, 10, 5]])
1455
+
1456
+ With ``mode='reflect'`` (the default), outer values are reflected at the
1457
+ edge of `input` to fill in missing values.
1458
+
1459
+ >>> b = np.array([[2, 0, 0],
1460
+ ... [1, 0, 0],
1461
+ ... [0, 0, 0]])
1462
+ >>> k = np.array([[0,1,0], [0,1,0], [0,1,0]])
1463
+ >>> ndimage.convolve(b, k, mode='reflect')
1464
+ array([[5, 0, 0],
1465
+ [3, 0, 0],
1466
+ [1, 0, 0]])
1467
+
1468
+ This includes diagonally at the corners.
1469
+
1470
+ >>> k = np.array([[1,0,0],[0,1,0],[0,0,1]])
1471
+ >>> ndimage.convolve(b, k)
1472
+ array([[4, 2, 0],
1473
+ [3, 2, 0],
1474
+ [1, 1, 0]])
1475
+
1476
+ With ``mode='nearest'``, the single nearest value in to an edge in
1477
+ `input` is repeated as many times as needed to match the overlapping
1478
+ `weights`.
1479
+
1480
+ >>> c = np.array([[2, 0, 1],
1481
+ ... [1, 0, 0],
1482
+ ... [0, 0, 0]])
1483
+ >>> k = np.array([[0, 1, 0],
1484
+ ... [0, 1, 0],
1485
+ ... [0, 1, 0],
1486
+ ... [0, 1, 0],
1487
+ ... [0, 1, 0]])
1488
+ >>> ndimage.convolve(c, k, mode='nearest')
1489
+ array([[7, 0, 3],
1490
+ [5, 0, 2],
1491
+ [3, 0, 1]])
1492
+
1493
+ """
1494
+ return _correlate_or_convolve(input, weights, output, mode, cval,
1495
+ origin, True, axes)
1496
+
1497
+
1498
+ @_ni_docstrings.docfiller
1499
+ def uniform_filter1d(input, size, axis=-1, output=None,
1500
+ mode="reflect", cval=0.0, origin=0):
1501
+ """Calculate a 1-D uniform filter along the given axis.
1502
+
1503
+ The lines of the array along the given axis are filtered with a
1504
+ uniform filter of given size.
1505
+
1506
+ Parameters
1507
+ ----------
1508
+ %(input)s
1509
+ size : int
1510
+ length of uniform filter
1511
+ %(axis)s
1512
+ %(output)s
1513
+ %(mode_reflect)s
1514
+ %(cval)s
1515
+ %(origin)s
1516
+
1517
+ Returns
1518
+ -------
1519
+ result : ndarray
1520
+ Filtered array. Has same shape as `input`.
1521
+
1522
+ Examples
1523
+ --------
1524
+ >>> from scipy.ndimage import uniform_filter1d
1525
+ >>> uniform_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
1526
+ array([4, 3, 4, 1, 4, 6, 6, 3])
1527
+ """
1528
+ input = np.asarray(input)
1529
+ axis = normalize_axis_index(axis, input.ndim)
1530
+ if size < 1:
1531
+ raise RuntimeError('incorrect filter size')
1532
+ complex_output = input.dtype.kind == 'c'
1533
+ output = _ni_support._get_output(output, input,
1534
+ complex_output=complex_output)
1535
+ if (size // 2 + origin < 0) or (size // 2 + origin >= size):
1536
+ raise ValueError('invalid origin')
1537
+ mode = _ni_support._extend_mode_to_code(mode)
1538
+ if not complex_output:
1539
+ _nd_image.uniform_filter1d(input, size, axis, output, mode, cval,
1540
+ origin)
1541
+ else:
1542
+ _nd_image.uniform_filter1d(input.real, size, axis, output.real, mode,
1543
+ np.real(cval), origin)
1544
+ _nd_image.uniform_filter1d(input.imag, size, axis, output.imag, mode,
1545
+ np.imag(cval), origin)
1546
+ return output
1547
+
1548
+
1549
+ @_ni_docstrings.docfiller
1550
+ def uniform_filter(input, size=3, output=None, mode="reflect",
1551
+ cval=0.0, origin=0, *, axes=None):
1552
+ """Multidimensional uniform filter.
1553
+
1554
+ Parameters
1555
+ ----------
1556
+ %(input)s
1557
+ size : int or sequence of ints, optional
1558
+ The sizes of the uniform filter are given for each axis as a
1559
+ sequence, or as a single number, in which case the size is
1560
+ equal for all axes.
1561
+ %(output)s
1562
+ %(mode_multiple)s
1563
+ %(cval)s
1564
+ %(origin_multiple)s
1565
+ axes : tuple of int or None, optional
1566
+ If None, `input` is filtered along all axes. Otherwise,
1567
+ `input` is filtered along the specified axes. When `axes` is
1568
+ specified, any tuples used for `size`, `origin`, and/or `mode`
1569
+ must match the length of `axes`. The ith entry in any of these tuples
1570
+ corresponds to the ith entry in `axes`.
1571
+
1572
+ Returns
1573
+ -------
1574
+ uniform_filter : ndarray
1575
+ Filtered array. Has the same shape as `input`.
1576
+
1577
+ Notes
1578
+ -----
1579
+ The multidimensional filter is implemented as a sequence of
1580
+ 1-D uniform filters. The intermediate arrays are stored
1581
+ in the same data type as the output. Therefore, for output types
1582
+ with a limited precision, the results may be imprecise because
1583
+ intermediate results may be stored with insufficient precision.
1584
+
1585
+ %(nan)s
1586
+
1587
+ Examples
1588
+ --------
1589
+ >>> from scipy import ndimage, datasets
1590
+ >>> import matplotlib.pyplot as plt
1591
+ >>> fig = plt.figure()
1592
+ >>> plt.gray() # show the filtered result in grayscale
1593
+ >>> ax1 = fig.add_subplot(121) # left side
1594
+ >>> ax2 = fig.add_subplot(122) # right side
1595
+ >>> ascent = datasets.ascent()
1596
+ >>> result = ndimage.uniform_filter(ascent, size=20)
1597
+ >>> ax1.imshow(ascent)
1598
+ >>> ax2.imshow(result)
1599
+ >>> plt.show()
1600
+ """
1601
+ input = np.asarray(input)
1602
+ output = _ni_support._get_output(output, input,
1603
+ complex_output=input.dtype.kind == 'c')
1604
+ axes = _ni_support._check_axes(axes, input.ndim)
1605
+ num_axes = len(axes)
1606
+ sizes = _ni_support._normalize_sequence(size, num_axes)
1607
+ origins = _ni_support._normalize_sequence(origin, num_axes)
1608
+ modes = _ni_support._normalize_sequence(mode, num_axes)
1609
+ axes = [(axes[ii], sizes[ii], origins[ii], modes[ii])
1610
+ for ii in range(num_axes) if sizes[ii] > 1]
1611
+ if len(axes) > 0:
1612
+ for axis, size, origin, mode in axes:
1613
+ uniform_filter1d(input, int(size), axis, output, mode,
1614
+ cval, origin)
1615
+ input = output
1616
+ else:
1617
+ output[...] = input[...]
1618
+ return output
1619
+
1620
+
1621
+ @_ni_docstrings.docfiller
1622
+ def minimum_filter1d(input, size, axis=-1, output=None,
1623
+ mode="reflect", cval=0.0, origin=0):
1624
+ """Calculate a 1-D minimum filter along the given axis.
1625
+
1626
+ The lines of the array along the given axis are filtered with a
1627
+ minimum filter of given size.
1628
+
1629
+ Parameters
1630
+ ----------
1631
+ %(input)s
1632
+ size : int
1633
+ length along which to calculate 1D minimum
1634
+ %(axis)s
1635
+ %(output)s
1636
+ %(mode_reflect)s
1637
+ %(cval)s
1638
+ %(origin)s
1639
+
1640
+ Returns
1641
+ -------
1642
+ result : ndarray.
1643
+ Filtered image. Has the same shape as `input`.
1644
+
1645
+ Notes
1646
+ -----
1647
+ This function implements the MINLIST algorithm [1]_, as described by
1648
+ Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being
1649
+ the `input` length, regardless of filter size.
1650
+
1651
+ References
1652
+ ----------
1653
+ .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777
1654
+ .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html
1655
+
1656
+
1657
+ Examples
1658
+ --------
1659
+ >>> from scipy.ndimage import minimum_filter1d
1660
+ >>> minimum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
1661
+ array([2, 0, 0, 0, 1, 1, 0, 0])
1662
+ """
1663
+ input = np.asarray(input)
1664
+ if np.iscomplexobj(input):
1665
+ raise TypeError('Complex type not supported')
1666
+ axis = normalize_axis_index(axis, input.ndim)
1667
+ if size < 1:
1668
+ raise RuntimeError('incorrect filter size')
1669
+ output = _ni_support._get_output(output, input)
1670
+ if (size // 2 + origin < 0) or (size // 2 + origin >= size):
1671
+ raise ValueError('invalid origin')
1672
+ mode = _ni_support._extend_mode_to_code(mode)
1673
+ _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,
1674
+ origin, 1)
1675
+ return output
1676
+
1677
+
1678
+ @_ni_docstrings.docfiller
1679
+ def maximum_filter1d(input, size, axis=-1, output=None,
1680
+ mode="reflect", cval=0.0, origin=0):
1681
+ """Calculate a 1-D maximum filter along the given axis.
1682
+
1683
+ The lines of the array along the given axis are filtered with a
1684
+ maximum filter of given size.
1685
+
1686
+ Parameters
1687
+ ----------
1688
+ %(input)s
1689
+ size : int
1690
+ Length along which to calculate the 1-D maximum.
1691
+ %(axis)s
1692
+ %(output)s
1693
+ %(mode_reflect)s
1694
+ %(cval)s
1695
+ %(origin)s
1696
+
1697
+ Returns
1698
+ -------
1699
+ maximum1d : ndarray, None
1700
+ Maximum-filtered array with same shape as input.
1701
+ None if `output` is not None
1702
+
1703
+ Notes
1704
+ -----
1705
+ This function implements the MAXLIST algorithm [1]_, as described by
1706
+ Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being
1707
+ the `input` length, regardless of filter size.
1708
+
1709
+ References
1710
+ ----------
1711
+ .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777
1712
+ .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html
1713
+
1714
+ Examples
1715
+ --------
1716
+ >>> from scipy.ndimage import maximum_filter1d
1717
+ >>> maximum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
1718
+ array([8, 8, 8, 4, 9, 9, 9, 9])
1719
+ """
1720
+ input = np.asarray(input)
1721
+ if np.iscomplexobj(input):
1722
+ raise TypeError('Complex type not supported')
1723
+ axis = normalize_axis_index(axis, input.ndim)
1724
+ if size < 1:
1725
+ raise RuntimeError('incorrect filter size')
1726
+ output = _ni_support._get_output(output, input)
1727
+ if (size // 2 + origin < 0) or (size // 2 + origin >= size):
1728
+ raise ValueError('invalid origin')
1729
+ mode = _ni_support._extend_mode_to_code(mode)
1730
+ _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,
1731
+ origin, 0)
1732
+ return output
1733
+
1734
+
1735
+ def _min_or_max_filter(input, size, footprint, structure, output, mode,
1736
+ cval, origin, minimum, axes=None):
1737
+ if (size is not None) and (footprint is not None):
1738
+ warnings.warn("ignoring size because footprint is set",
1739
+ UserWarning, stacklevel=3)
1740
+ if structure is None:
1741
+ if footprint is None:
1742
+ if size is None:
1743
+ raise RuntimeError("no footprint provided")
1744
+ separable = True
1745
+ else:
1746
+ footprint = np.asarray(footprint, dtype=bool)
1747
+ if not footprint.any():
1748
+ raise ValueError("All-zero footprint is not supported.")
1749
+ if footprint.all():
1750
+ size = footprint.shape
1751
+ footprint = None
1752
+ separable = True
1753
+ else:
1754
+ separable = False
1755
+ else:
1756
+ structure = np.asarray(structure, dtype=np.float64)
1757
+ separable = False
1758
+ if footprint is None:
1759
+ footprint = np.ones(structure.shape, bool)
1760
+ else:
1761
+ footprint = np.asarray(footprint, dtype=bool)
1762
+ input = np.asarray(input)
1763
+ if np.iscomplexobj(input):
1764
+ raise TypeError("Complex type not supported")
1765
+ output = _ni_support._get_output(output, input)
1766
+ temp_needed = np.may_share_memory(input, output)
1767
+ if temp_needed:
1768
+ # input and output arrays cannot share memory
1769
+ temp = output
1770
+ output = _ni_support._get_output(output.dtype, input)
1771
+ axes = _ni_support._check_axes(axes, input.ndim)
1772
+ num_axes = len(axes)
1773
+ if separable:
1774
+ origins = _ni_support._normalize_sequence(origin, num_axes)
1775
+ sizes = _ni_support._normalize_sequence(size, num_axes)
1776
+ modes = _ni_support._normalize_sequence(mode, num_axes)
1777
+ axes = [(axes[ii], sizes[ii], origins[ii], modes[ii])
1778
+ for ii in range(len(axes)) if sizes[ii] > 1]
1779
+ if minimum:
1780
+ filter_ = minimum_filter1d
1781
+ else:
1782
+ filter_ = maximum_filter1d
1783
+ if len(axes) > 0:
1784
+ for axis, size, origin, mode in axes:
1785
+ filter_(input, int(size), axis, output, mode, cval, origin)
1786
+ input = output
1787
+ else:
1788
+ output[...] = input[...]
1789
+ else:
1790
+ # expand origins and footprint if num_axes < input.ndim
1791
+ footprint = _expand_footprint(input.ndim, axes, footprint)
1792
+ origins = _expand_origin(input.ndim, axes, origin)
1793
+
1794
+ fshape = [ii for ii in footprint.shape if ii > 0]
1795
+ if len(fshape) != input.ndim:
1796
+ raise RuntimeError(f"footprint.ndim ({footprint.ndim}) must match "
1797
+ f"len(axes) ({len(axes)})")
1798
+ for origin, lenf in zip(origins, fshape):
1799
+ if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
1800
+ raise ValueError("invalid origin")
1801
+ if not footprint.flags.contiguous:
1802
+ footprint = footprint.copy()
1803
+ if structure is not None:
1804
+ if len(structure.shape) != num_axes:
1805
+ raise RuntimeError("structure array has incorrect shape")
1806
+ if num_axes != structure.ndim:
1807
+ structure = np.expand_dims(
1808
+ structure,
1809
+ tuple(ax for ax in range(structure.ndim) if ax not in axes)
1810
+ )
1811
+ if not structure.flags.contiguous:
1812
+ structure = structure.copy()
1813
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
1814
+ raise RuntimeError(
1815
+ "A sequence of modes is not supported for non-separable "
1816
+ "footprints")
1817
+ mode = _ni_support._extend_mode_to_code(mode)
1818
+ _nd_image.min_or_max_filter(input, footprint, structure, output,
1819
+ mode, cval, origins, minimum)
1820
+ if temp_needed:
1821
+ temp[...] = output
1822
+ output = temp
1823
+ return output
1824
+
1825
+
1826
+ @_ni_docstrings.docfiller
1827
+ def minimum_filter(input, size=None, footprint=None, output=None,
1828
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
1829
+ """Calculate a multidimensional minimum filter.
1830
+
1831
+ Parameters
1832
+ ----------
1833
+ %(input)s
1834
+ %(size_foot)s
1835
+ %(output)s
1836
+ %(mode_multiple)s
1837
+ %(cval)s
1838
+ %(origin_multiple)s
1839
+ axes : tuple of int or None, optional
1840
+ If None, `input` is filtered along all axes. Otherwise,
1841
+ `input` is filtered along the specified axes. When `axes` is
1842
+ specified, any tuples used for `size`, `origin`, and/or `mode`
1843
+ must match the length of `axes`. The ith entry in any of these tuples
1844
+ corresponds to the ith entry in `axes`.
1845
+
1846
+ Returns
1847
+ -------
1848
+ minimum_filter : ndarray
1849
+ Filtered array. Has the same shape as `input`.
1850
+
1851
+ Notes
1852
+ -----
1853
+ A sequence of modes (one per axis) is only supported when the footprint is
1854
+ separable. Otherwise, a single mode string must be provided.
1855
+
1856
+ Examples
1857
+ --------
1858
+ >>> from scipy import ndimage, datasets
1859
+ >>> import matplotlib.pyplot as plt
1860
+ >>> fig = plt.figure()
1861
+ >>> plt.gray() # show the filtered result in grayscale
1862
+ >>> ax1 = fig.add_subplot(121) # left side
1863
+ >>> ax2 = fig.add_subplot(122) # right side
1864
+ >>> ascent = datasets.ascent()
1865
+ >>> result = ndimage.minimum_filter(ascent, size=20)
1866
+ >>> ax1.imshow(ascent)
1867
+ >>> ax2.imshow(result)
1868
+ >>> plt.show()
1869
+ """
1870
+ return _min_or_max_filter(input, size, footprint, None, output, mode,
1871
+ cval, origin, 1, axes)
1872
+
1873
+
1874
+ @_ni_docstrings.docfiller
1875
+ def maximum_filter(input, size=None, footprint=None, output=None,
1876
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
1877
+ """Calculate a multidimensional maximum filter.
1878
+
1879
+ Parameters
1880
+ ----------
1881
+ %(input)s
1882
+ %(size_foot)s
1883
+ %(output)s
1884
+ %(mode_multiple)s
1885
+ %(cval)s
1886
+ %(origin_multiple)s
1887
+ axes : tuple of int or None, optional
1888
+ If None, `input` is filtered along all axes. Otherwise,
1889
+ `input` is filtered along the specified axes. When `axes` is
1890
+ specified, any tuples used for `size`, `origin`, and/or `mode`
1891
+ must match the length of `axes`. The ith entry in any of these tuples
1892
+ corresponds to the ith entry in `axes`.
1893
+
1894
+ Returns
1895
+ -------
1896
+ maximum_filter : ndarray
1897
+ Filtered array. Has the same shape as `input`.
1898
+
1899
+ Notes
1900
+ -----
1901
+ A sequence of modes (one per axis) is only supported when the footprint is
1902
+ separable. Otherwise, a single mode string must be provided.
1903
+
1904
+ %(nan)s
1905
+
1906
+ Examples
1907
+ --------
1908
+ >>> from scipy import ndimage, datasets
1909
+ >>> import matplotlib.pyplot as plt
1910
+ >>> fig = plt.figure()
1911
+ >>> plt.gray() # show the filtered result in grayscale
1912
+ >>> ax1 = fig.add_subplot(121) # left side
1913
+ >>> ax2 = fig.add_subplot(122) # right side
1914
+ >>> ascent = datasets.ascent()
1915
+ >>> result = ndimage.maximum_filter(ascent, size=20)
1916
+ >>> ax1.imshow(ascent)
1917
+ >>> ax2.imshow(result)
1918
+ >>> plt.show()
1919
+ """
1920
+ return _min_or_max_filter(input, size, footprint, None, output, mode,
1921
+ cval, origin, 0, axes)
1922
+
1923
+
1924
+ @_ni_docstrings.docfiller
1925
+ def _rank_filter(input, rank, size=None, footprint=None, output=None,
1926
+ mode="reflect", cval=0.0, origin=0, operation='rank',
1927
+ axes=None):
1928
+ if (size is not None) and (footprint is not None):
1929
+ warnings.warn("ignoring size because footprint is set",
1930
+ UserWarning, stacklevel=3)
1931
+ input = np.asarray(input)
1932
+ if np.iscomplexobj(input):
1933
+ raise TypeError('Complex type not supported')
1934
+ axes = _ni_support._check_axes(axes, input.ndim)
1935
+ num_axes = len(axes)
1936
+ if footprint is None:
1937
+ if size is None:
1938
+ raise RuntimeError("no footprint or filter size provided")
1939
+ sizes = _ni_support._normalize_sequence(size, num_axes)
1940
+ footprint = np.ones(sizes, dtype=bool)
1941
+ else:
1942
+ footprint = np.asarray(footprint, dtype=bool)
1943
+ # expand origins, footprint and modes if num_axes < input.ndim
1944
+ footprint = _expand_footprint(input.ndim, axes, footprint)
1945
+ origins = _expand_origin(input.ndim, axes, origin)
1946
+ mode = _expand_mode(input.ndim, axes, mode)
1947
+
1948
+ fshape = [ii for ii in footprint.shape if ii > 0]
1949
+ if len(fshape) != input.ndim:
1950
+ raise RuntimeError(f"footprint.ndim ({footprint.ndim}) must match "
1951
+ f"len(axes) ({len(axes)})")
1952
+ for origin, lenf in zip(origins, fshape):
1953
+ if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
1954
+ raise ValueError('invalid origin')
1955
+ if not footprint.flags.contiguous:
1956
+ footprint = footprint.copy()
1957
+ filter_size = np.where(footprint, 1, 0).sum()
1958
+ if operation == 'median':
1959
+ rank = filter_size // 2
1960
+ elif operation == 'percentile':
1961
+ percentile = rank
1962
+ if percentile < 0.0:
1963
+ percentile += 100.0
1964
+ if percentile < 0 or percentile > 100:
1965
+ raise RuntimeError('invalid percentile')
1966
+ if percentile == 100.0:
1967
+ rank = filter_size - 1
1968
+ else:
1969
+ rank = int(float(filter_size) * percentile / 100.0)
1970
+ if rank < 0:
1971
+ rank += filter_size
1972
+ if rank < 0 or rank >= filter_size:
1973
+ raise RuntimeError('rank not within filter footprint size')
1974
+ if rank == 0:
1975
+ return minimum_filter(input, None, footprint, output, mode, cval,
1976
+ origins, axes=None)
1977
+ elif rank == filter_size - 1:
1978
+ return maximum_filter(input, None, footprint, output, mode, cval,
1979
+ origins, axes=None)
1980
+ else:
1981
+ output = _ni_support._get_output(output, input)
1982
+ temp_needed = np.may_share_memory(input, output)
1983
+ if temp_needed:
1984
+ # input and output arrays cannot share memory
1985
+ temp = output
1986
+ output = _ni_support._get_output(output.dtype, input)
1987
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
1988
+ raise RuntimeError(
1989
+ "A sequence of modes is not supported by non-separable rank "
1990
+ "filters")
1991
+ mode = _ni_support._extend_mode_to_code(mode, is_filter=True)
1992
+ # Some corner cases are currently not allowed to use the
1993
+ # "new"/fast 1D rank filter code, including when the
1994
+ # footprint is large compared to the array size.
1995
+ # See discussion in gh-23293; longer-term it may be possible
1996
+ # to allow the fast path for these corner cases as well,
1997
+ # if algorithmic fixes are found.
1998
+ lim2 = input.size - ((footprint.size - 1) // 2 - origin)
1999
+ if input.ndim == 1 and ((lim2 >= 0) or (input.size == 1)):
2000
+ if input.dtype in (np.int64, np.float64, np.float32):
2001
+ x = input
2002
+ x_out = output
2003
+ elif input.dtype == np.float16:
2004
+ x = input.astype('float32')
2005
+ x_out = np.empty(x.shape, dtype='float32')
2006
+ elif np.result_type(input, np.int64) == np.int64:
2007
+ x = input.astype('int64')
2008
+ x_out = np.empty(x.shape, dtype='int64')
2009
+ elif input.dtype.kind in 'biu':
2010
+ # cast any other boolean, integer or unsigned type to int64
2011
+ x = input.astype('int64')
2012
+ x_out = np.empty(x.shape, dtype='int64')
2013
+ else:
2014
+ raise RuntimeError('Unsupported array type')
2015
+ cval = x.dtype.type(cval)
2016
+ _rank_filter_1d.rank_filter(x, rank, footprint.size, x_out, mode, cval,
2017
+ origin)
2018
+ if input.dtype not in (np.int64, np.float64, np.float32):
2019
+ np.copyto(output, x_out, casting='unsafe')
2020
+ else:
2021
+ _nd_image.rank_filter(input, rank, footprint, output, mode, cval, origins)
2022
+ if temp_needed:
2023
+ temp[...] = output
2024
+ output = temp
2025
+ return output
2026
+
2027
+
2028
+ @_ni_docstrings.docfiller
2029
+ def rank_filter(input, rank, size=None, footprint=None, output=None,
2030
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
2031
+ """Calculate a multidimensional rank filter.
2032
+
2033
+ Parameters
2034
+ ----------
2035
+ %(input)s
2036
+ rank : int
2037
+ The rank parameter may be less than zero, i.e., rank = -1
2038
+ indicates the largest element.
2039
+ %(size_foot)s
2040
+ %(output)s
2041
+ %(mode_reflect)s
2042
+ %(cval)s
2043
+ %(origin_multiple)s
2044
+ axes : tuple of int or None, optional
2045
+ If None, `input` is filtered along all axes. Otherwise,
2046
+ `input` is filtered along the specified axes. When `axes` is
2047
+ specified, any tuples used for `size`, `origin`, and/or `mode`
2048
+ must match the length of `axes`. The ith entry in any of these tuples
2049
+ corresponds to the ith entry in `axes`.
2050
+
2051
+ Returns
2052
+ -------
2053
+ rank_filter : ndarray
2054
+ Filtered array. Has the same shape as `input`.
2055
+
2056
+ Examples
2057
+ --------
2058
+ >>> from scipy import ndimage, datasets
2059
+ >>> import matplotlib.pyplot as plt
2060
+ >>> fig = plt.figure()
2061
+ >>> plt.gray() # show the filtered result in grayscale
2062
+ >>> ax1 = fig.add_subplot(121) # left side
2063
+ >>> ax2 = fig.add_subplot(122) # right side
2064
+ >>> ascent = datasets.ascent()
2065
+ >>> result = ndimage.rank_filter(ascent, rank=42, size=20)
2066
+ >>> ax1.imshow(ascent)
2067
+ >>> ax2.imshow(result)
2068
+ >>> plt.show()
2069
+ """
2070
+ rank = operator.index(rank)
2071
+ return _rank_filter(input, rank, size, footprint, output, mode, cval,
2072
+ origin, 'rank', axes=axes)
2073
+
2074
+
2075
+ @_ni_docstrings.docfiller
2076
+ def median_filter(input, size=None, footprint=None, output=None,
2077
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
2078
+ """
2079
+ Calculate a multidimensional median filter.
2080
+
2081
+ Parameters
2082
+ ----------
2083
+ %(input)s
2084
+ %(size_foot)s
2085
+ %(output)s
2086
+ %(mode_reflect)s
2087
+ %(cval)s
2088
+ %(origin_multiple)s
2089
+ axes : tuple of int or None, optional
2090
+ If None, `input` is filtered along all axes. Otherwise,
2091
+ `input` is filtered along the specified axes. When `axes` is
2092
+ specified, any tuples used for `size`, `origin`, and/or `mode`
2093
+ must match the length of `axes`. The ith entry in any of these tuples
2094
+ corresponds to the ith entry in `axes`.
2095
+
2096
+ Returns
2097
+ -------
2098
+ median_filter : ndarray
2099
+ Filtered array. Has the same shape as `input`.
2100
+
2101
+ See Also
2102
+ --------
2103
+ scipy.signal.medfilt2d
2104
+
2105
+ Notes
2106
+ -----
2107
+ For 2-dimensional images with ``uint8``, ``float32`` or ``float64`` dtypes
2108
+ the specialised function `scipy.signal.medfilt2d` may be faster. It is
2109
+ however limited to constant mode with ``cval=0``.
2110
+
2111
+ The filter always returns the argument that would appear at index ``n // 2`` in
2112
+ a sorted array, where ``n`` is the number of elements in the footprint of the
2113
+ filter. Note that this differs from the conventional definition of the median
2114
+ when ``n`` is even. Also, this function does not support the ``float16`` dtype,
2115
+ behavior in the presence of NaNs is undefined, and memory consumption scales with
2116
+ ``n**4``. For ``float16`` support, greater control over the definition of the
2117
+ filter, and to limit memory usage, consider using `vectorized_filter` with
2118
+ NumPy functions `np.median` or `np.nanmedian`.
2119
+
2120
+ Examples
2121
+ --------
2122
+ >>> from scipy import ndimage, datasets
2123
+ >>> import matplotlib.pyplot as plt
2124
+ >>> fig = plt.figure()
2125
+ >>> plt.gray() # show the filtered result in grayscale
2126
+ >>> ax1 = fig.add_subplot(121) # left side
2127
+ >>> ax2 = fig.add_subplot(122) # right side
2128
+ >>> ascent = datasets.ascent()
2129
+ >>> result = ndimage.median_filter(ascent, size=20)
2130
+ >>> ax1.imshow(ascent)
2131
+ >>> ax2.imshow(result)
2132
+ >>> plt.show()
2133
+ """
2134
+ return _rank_filter(input, 0, size, footprint, output, mode, cval,
2135
+ origin, 'median', axes=axes)
2136
+
2137
+
2138
+ @_ni_docstrings.docfiller
2139
+ def percentile_filter(input, percentile, size=None, footprint=None,
2140
+ output=None, mode="reflect", cval=0.0, origin=0, *,
2141
+ axes=None):
2142
+ """Calculate a multidimensional percentile filter.
2143
+
2144
+ Parameters
2145
+ ----------
2146
+ %(input)s
2147
+ percentile : scalar
2148
+ The percentile parameter may be less than zero, i.e.,
2149
+ percentile = -20 equals percentile = 80
2150
+ %(size_foot)s
2151
+ %(output)s
2152
+ %(mode_reflect)s
2153
+ %(cval)s
2154
+ %(origin_multiple)s
2155
+ axes : tuple of int or None, optional
2156
+ If None, `input` is filtered along all axes. Otherwise,
2157
+ `input` is filtered along the specified axes. When `axes` is
2158
+ specified, any tuples used for `size`, `origin`, and/or `mode`
2159
+ must match the length of `axes`. The ith entry in any of these tuples
2160
+ corresponds to the ith entry in `axes`.
2161
+
2162
+ Returns
2163
+ -------
2164
+ percentile_filter : ndarray
2165
+ Filtered array. Has the same shape as `input`.
2166
+
2167
+ Examples
2168
+ --------
2169
+ >>> from scipy import ndimage, datasets
2170
+ >>> import matplotlib.pyplot as plt
2171
+ >>> fig = plt.figure()
2172
+ >>> plt.gray() # show the filtered result in grayscale
2173
+ >>> ax1 = fig.add_subplot(121) # left side
2174
+ >>> ax2 = fig.add_subplot(122) # right side
2175
+ >>> ascent = datasets.ascent()
2176
+ >>> result = ndimage.percentile_filter(ascent, percentile=20, size=20)
2177
+ >>> ax1.imshow(ascent)
2178
+ >>> ax2.imshow(result)
2179
+ >>> plt.show()
2180
+ """
2181
+ return _rank_filter(input, percentile, size, footprint, output, mode,
2182
+ cval, origin, 'percentile', axes=axes)
2183
+
2184
+
2185
+ @_ni_docstrings.docfiller
2186
+ def generic_filter1d(input, function, filter_size, axis=-1,
2187
+ output=None, mode="reflect", cval=0.0, origin=0,
2188
+ extra_arguments=(), extra_keywords=None):
2189
+ """Calculate a 1-D filter along the given axis.
2190
+
2191
+ `generic_filter1d` iterates over the lines of the array, calling the
2192
+ given function at each line. The arguments of the line are the
2193
+ input line, and the output line. The input and output lines are 1-D
2194
+ double arrays. The input line is extended appropriately according
2195
+ to the filter size and origin. The output line must be modified
2196
+ in-place with the result.
2197
+
2198
+ Parameters
2199
+ ----------
2200
+ %(input)s
2201
+ function : {callable, scipy.LowLevelCallable}
2202
+ Function to apply along given axis.
2203
+ filter_size : scalar
2204
+ Length of the filter.
2205
+ %(axis)s
2206
+ %(output)s
2207
+ %(mode_reflect)s
2208
+ %(cval)s
2209
+ %(origin)s
2210
+ %(extra_arguments)s
2211
+ %(extra_keywords)s
2212
+
2213
+ Returns
2214
+ -------
2215
+ generic_filter1d : ndarray
2216
+ Filtered array. Has the same shape as `input`.
2217
+
2218
+ Notes
2219
+ -----
2220
+ This function also accepts low-level callback functions with one of
2221
+ the following signatures and wrapped in `scipy.LowLevelCallable`:
2222
+
2223
+ .. code:: c
2224
+
2225
+ int function(double *input_line, npy_intp input_length,
2226
+ double *output_line, npy_intp output_length,
2227
+ void *user_data)
2228
+ int function(double *input_line, intptr_t input_length,
2229
+ double *output_line, intptr_t output_length,
2230
+ void *user_data)
2231
+
2232
+ The calling function iterates over the lines of the input and output
2233
+ arrays, calling the callback function at each line. The current line
2234
+ is extended according to the border conditions set by the calling
2235
+ function, and the result is copied into the array that is passed
2236
+ through ``input_line``. The length of the input line (after extension)
2237
+ is passed through ``input_length``. The callback function should apply
2238
+ the filter and store the result in the array passed through
2239
+ ``output_line``. The length of the output line is passed through
2240
+ ``output_length``. ``user_data`` is the data pointer provided
2241
+ to `scipy.LowLevelCallable` as-is.
2242
+
2243
+ The callback function must return an integer error status that is zero
2244
+ if something went wrong and one otherwise. If an error occurs, you should
2245
+ normally set the python error status with an informative message
2246
+ before returning, otherwise a default error message is set by the
2247
+ calling function.
2248
+
2249
+ In addition, some other low-level function pointer specifications
2250
+ are accepted, but these are for backward compatibility only and should
2251
+ not be used in new code.
2252
+
2253
+ """
2254
+ if extra_keywords is None:
2255
+ extra_keywords = {}
2256
+ input = np.asarray(input)
2257
+ if np.iscomplexobj(input):
2258
+ raise TypeError('Complex type not supported')
2259
+ output = _ni_support._get_output(output, input)
2260
+ if filter_size < 1:
2261
+ raise RuntimeError('invalid filter size')
2262
+ axis = normalize_axis_index(axis, input.ndim)
2263
+ if (filter_size // 2 + origin < 0) or (filter_size // 2 + origin >=
2264
+ filter_size):
2265
+ raise ValueError('invalid origin')
2266
+ mode = _ni_support._extend_mode_to_code(mode)
2267
+ _nd_image.generic_filter1d(input, function, filter_size, axis, output,
2268
+ mode, cval, origin, extra_arguments,
2269
+ extra_keywords)
2270
+ return output
2271
+
2272
+
2273
+ @_ni_docstrings.docfiller
2274
+ def generic_filter(input, function, size=None, footprint=None,
2275
+ output=None, mode="reflect", cval=0.0, origin=0,
2276
+ extra_arguments=(), extra_keywords=None, *, axes=None):
2277
+ """Calculate a multidimensional filter using the given function.
2278
+
2279
+ At each element the provided function is called. The input values
2280
+ within the filter footprint at that element are passed to the function
2281
+ as a 1-D array of double values.
2282
+
2283
+ Parameters
2284
+ ----------
2285
+ %(input)s
2286
+ function : {callable, scipy.LowLevelCallable}
2287
+ Function to apply at each element.
2288
+ %(size_foot)s
2289
+ %(output)s
2290
+ %(mode_reflect)s
2291
+ %(cval)s
2292
+ %(origin_multiple)s
2293
+ %(extra_arguments)s
2294
+ %(extra_keywords)s
2295
+ axes : tuple of int or None, optional
2296
+ If None, `input` is filtered along all axes. Otherwise,
2297
+ `input` is filtered along the specified axes. When `axes` is
2298
+ specified, any tuples used for `size` or `origin` must match the length
2299
+ of `axes`. The ith entry in any of these tuples corresponds to the ith
2300
+ entry in `axes`.
2301
+
2302
+ Returns
2303
+ -------
2304
+ output : ndarray
2305
+ Filtered array. Has the same shape as `input`.
2306
+
2307
+ See Also
2308
+ --------
2309
+ vectorized_filter : similar functionality, but optimized for vectorized callables
2310
+
2311
+ Notes
2312
+ -----
2313
+ This function is ideal for use with instances of `scipy.LowLevelCallable`;
2314
+ for vectorized, pure-Python callables, consider `vectorized_filter` for improved
2315
+ performance.
2316
+
2317
+ Low-level callback functions must have one of the following signatures:
2318
+
2319
+ .. code:: c
2320
+
2321
+ int callback(double *buffer, npy_intp filter_size,
2322
+ double *return_value, void *user_data)
2323
+ int callback(double *buffer, intptr_t filter_size,
2324
+ double *return_value, void *user_data)
2325
+
2326
+ The calling function iterates over the elements of the input and
2327
+ output arrays, calling the callback function at each element. The
2328
+ elements within the footprint of the filter at the current element are
2329
+ passed through the ``buffer`` parameter, and the number of elements
2330
+ within the footprint through ``filter_size``. The calculated value is
2331
+ returned in ``return_value``. ``user_data`` is the data pointer provided
2332
+ to `scipy.LowLevelCallable` as-is.
2333
+
2334
+ The callback function must return an integer error status that is zero
2335
+ if something went wrong and one otherwise. If an error occurs, you should
2336
+ normally set the python error status with an informative message
2337
+ before returning, otherwise a default error message is set by the
2338
+ calling function.
2339
+
2340
+ In addition, some other low-level function pointer specifications
2341
+ are accepted, but these are for backward compatibility only and should
2342
+ not be used in new code.
2343
+
2344
+ Examples
2345
+ --------
2346
+ Import the necessary modules and load the example image used for
2347
+ filtering.
2348
+
2349
+ >>> import numpy as np
2350
+ >>> from scipy import datasets
2351
+ >>> from scipy.ndimage import zoom, generic_filter
2352
+ >>> import matplotlib.pyplot as plt
2353
+ >>> ascent = zoom(datasets.ascent(), 0.5)
2354
+
2355
+ Compute a maximum filter with kernel size 5 by passing a simple NumPy
2356
+ aggregation function as argument to `function`.
2357
+
2358
+ >>> maximum_filter_result = generic_filter(ascent, np.amax, [5, 5])
2359
+
2360
+ While a maximum filter could also directly be obtained using
2361
+ `maximum_filter`, `generic_filter` allows generic Python function or
2362
+ `scipy.LowLevelCallable` to be used as a filter. Here, we compute the
2363
+ range between maximum and minimum value as an example for a kernel size
2364
+ of 5.
2365
+
2366
+ >>> def custom_filter(image):
2367
+ ... return np.amax(image) - np.amin(image)
2368
+ >>> custom_filter_result = generic_filter(ascent, custom_filter, [5, 5])
2369
+
2370
+ Plot the original and filtered images.
2371
+
2372
+ >>> fig, axes = plt.subplots(3, 1, figsize=(3, 9))
2373
+ >>> plt.gray() # show the filtered result in grayscale
2374
+ >>> top, middle, bottom = axes
2375
+ >>> for ax in axes:
2376
+ ... ax.set_axis_off() # remove coordinate system
2377
+ >>> top.imshow(ascent)
2378
+ >>> top.set_title("Original image")
2379
+ >>> middle.imshow(maximum_filter_result)
2380
+ >>> middle.set_title("Maximum filter, Kernel: 5x5")
2381
+ >>> bottom.imshow(custom_filter_result)
2382
+ >>> bottom.set_title("Custom filter, Kernel: 5x5")
2383
+ >>> fig.tight_layout()
2384
+
2385
+ """
2386
+ if (size is not None) and (footprint is not None):
2387
+ warnings.warn("ignoring size because footprint is set",
2388
+ UserWarning, stacklevel=2)
2389
+ if extra_keywords is None:
2390
+ extra_keywords = {}
2391
+ input = np.asarray(input)
2392
+ if np.iscomplexobj(input):
2393
+ raise TypeError('Complex type not supported')
2394
+ axes = _ni_support._check_axes(axes, input.ndim)
2395
+ num_axes = len(axes)
2396
+ if footprint is None:
2397
+ if size is None:
2398
+ raise RuntimeError("no footprint or filter size provided")
2399
+ sizes = _ni_support._normalize_sequence(size, num_axes)
2400
+ footprint = np.ones(sizes, dtype=bool)
2401
+ else:
2402
+ footprint = np.asarray(footprint, dtype=bool)
2403
+
2404
+ # expand origins, footprint if num_axes < input.ndim
2405
+ footprint = _expand_footprint(input.ndim, axes, footprint)
2406
+ origins = _expand_origin(input.ndim, axes, origin)
2407
+
2408
+ fshape = [ii for ii in footprint.shape if ii > 0]
2409
+ if len(fshape) != input.ndim:
2410
+ raise RuntimeError(f"footprint.ndim ({footprint.ndim}) "
2411
+ f"must match len(axes) ({num_axes})")
2412
+ for origin, lenf in zip(origins, fshape):
2413
+ if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
2414
+ raise ValueError('invalid origin')
2415
+ if not footprint.flags.contiguous:
2416
+ footprint = footprint.copy()
2417
+ output = _ni_support._get_output(output, input)
2418
+
2419
+ mode = _ni_support._extend_mode_to_code(mode)
2420
+ _nd_image.generic_filter(input, function, footprint, output, mode,
2421
+ cval, origins, extra_arguments, extra_keywords)
2422
+ return output
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_fourier.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2003-2005 Peter J. Verveer
2
+ #
3
+ # Redistribution and use in source and binary forms, with or without
4
+ # modification, are permitted provided that the following conditions
5
+ # are met:
6
+ #
7
+ # 1. Redistributions of source code must retain the above copyright
8
+ # notice, this list of conditions and the following disclaimer.
9
+ #
10
+ # 2. Redistributions in binary form must reproduce the above
11
+ # copyright notice, this list of conditions and the following
12
+ # disclaimer in the documentation and/or other materials provided
13
+ # with the distribution.
14
+ #
15
+ # 3. The name of the author may not be used to endorse or promote
16
+ # products derived from this software without specific prior
17
+ # written permission.
18
+ #
19
+ # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
20
+ # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21
+ # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
23
+ # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
25
+ # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
27
+ # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28
+ # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29
+ # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
+
31
+ import numpy as np
32
+ from scipy._lib._util import normalize_axis_index
33
+ from . import _ni_support
34
+ from . import _nd_image
35
+
36
+ __all__ = ['fourier_gaussian', 'fourier_uniform', 'fourier_ellipsoid',
37
+ 'fourier_shift']
38
+
39
+
40
+ def _get_output_fourier(output, input):
41
+ if output is None:
42
+ if input.dtype.type in [np.complex64, np.complex128, np.float32]:
43
+ output = np.zeros(input.shape, dtype=input.dtype)
44
+ else:
45
+ output = np.zeros(input.shape, dtype=np.float64)
46
+ elif type(output) is type:
47
+ if output not in [np.complex64, np.complex128,
48
+ np.float32, np.float64]:
49
+ raise RuntimeError("output type not supported")
50
+ output = np.zeros(input.shape, dtype=output)
51
+ elif output.shape != input.shape:
52
+ raise RuntimeError("output shape not correct")
53
+ return output
54
+
55
+
56
+ def _get_output_fourier_complex(output, input):
57
+ if output is None:
58
+ if input.dtype.type in [np.complex64, np.complex128]:
59
+ output = np.zeros(input.shape, dtype=input.dtype)
60
+ else:
61
+ output = np.zeros(input.shape, dtype=np.complex128)
62
+ elif type(output) is type:
63
+ if output not in [np.complex64, np.complex128]:
64
+ raise RuntimeError("output type not supported")
65
+ output = np.zeros(input.shape, dtype=output)
66
+ elif output.shape != input.shape:
67
+ raise RuntimeError("output shape not correct")
68
+ return output
69
+
70
+
71
+ def fourier_gaussian(input, sigma, n=-1, axis=-1, output=None):
72
+ """
73
+ Multidimensional Gaussian fourier filter.
74
+
75
+ The array is multiplied with the fourier transform of a Gaussian
76
+ kernel.
77
+
78
+ Parameters
79
+ ----------
80
+ input : array_like
81
+ The input array.
82
+ sigma : float or sequence
83
+ The sigma of the Gaussian kernel. If a float, `sigma` is the same for
84
+ all axes. If a sequence, `sigma` has to contain one value for each
85
+ axis.
86
+ n : int, optional
87
+ If `n` is negative (default), then the input is assumed to be the
88
+ result of a complex fft.
89
+ If `n` is larger than or equal to zero, the input is assumed to be the
90
+ result of a real fft, and `n` gives the length of the array before
91
+ transformation along the real transform direction.
92
+ axis : int, optional
93
+ The axis of the real transform.
94
+ output : ndarray, optional
95
+ If given, the result of filtering the input is placed in this array.
96
+
97
+ Returns
98
+ -------
99
+ fourier_gaussian : ndarray
100
+ The filtered input.
101
+
102
+ Examples
103
+ --------
104
+ >>> from scipy import ndimage, datasets
105
+ >>> import numpy.fft
106
+ >>> import matplotlib.pyplot as plt
107
+ >>> fig, (ax1, ax2) = plt.subplots(1, 2)
108
+ >>> plt.gray() # show the filtered result in grayscale
109
+ >>> ascent = datasets.ascent()
110
+ >>> input_ = numpy.fft.fft2(ascent)
111
+ >>> result = ndimage.fourier_gaussian(input_, sigma=4)
112
+ >>> result = numpy.fft.ifft2(result)
113
+ >>> ax1.imshow(ascent)
114
+ >>> ax2.imshow(result.real) # the imaginary part is an artifact
115
+ >>> plt.show()
116
+ """
117
+ input = np.asarray(input)
118
+ output = _get_output_fourier(output, input)
119
+ axis = normalize_axis_index(axis, input.ndim)
120
+ sigmas = _ni_support._normalize_sequence(sigma, input.ndim)
121
+ sigmas = np.asarray(sigmas, dtype=np.float64)
122
+ if not sigmas.flags.contiguous:
123
+ sigmas = sigmas.copy()
124
+
125
+ _nd_image.fourier_filter(input, sigmas, n, axis, output, 0)
126
+ return output
127
+
128
+
129
+ def fourier_uniform(input, size, n=-1, axis=-1, output=None):
130
+ """
131
+ Multidimensional uniform fourier filter.
132
+
133
+ The array is multiplied with the Fourier transform of a box of given
134
+ size.
135
+
136
+ Parameters
137
+ ----------
138
+ input : array_like
139
+ The input array.
140
+ size : float or sequence
141
+ The size of the box used for filtering.
142
+ If a float, `size` is the same for all axes. If a sequence, `size` has
143
+ to contain one value for each axis.
144
+ n : int, optional
145
+ If `n` is negative (default), then the input is assumed to be the
146
+ result of a complex fft.
147
+ If `n` is larger than or equal to zero, the input is assumed to be the
148
+ result of a real fft, and `n` gives the length of the array before
149
+ transformation along the real transform direction.
150
+ axis : int, optional
151
+ The axis of the real transform.
152
+ output : ndarray, optional
153
+ If given, the result of filtering the input is placed in this array.
154
+
155
+ Returns
156
+ -------
157
+ fourier_uniform : ndarray
158
+ The filtered input.
159
+
160
+ Examples
161
+ --------
162
+ >>> from scipy import ndimage, datasets
163
+ >>> import numpy.fft
164
+ >>> import matplotlib.pyplot as plt
165
+ >>> fig, (ax1, ax2) = plt.subplots(1, 2)
166
+ >>> plt.gray() # show the filtered result in grayscale
167
+ >>> ascent = datasets.ascent()
168
+ >>> input_ = numpy.fft.fft2(ascent)
169
+ >>> result = ndimage.fourier_uniform(input_, size=20)
170
+ >>> result = numpy.fft.ifft2(result)
171
+ >>> ax1.imshow(ascent)
172
+ >>> ax2.imshow(result.real) # the imaginary part is an artifact
173
+ >>> plt.show()
174
+ """
175
+ input = np.asarray(input)
176
+ output = _get_output_fourier(output, input)
177
+ axis = normalize_axis_index(axis, input.ndim)
178
+ sizes = _ni_support._normalize_sequence(size, input.ndim)
179
+ sizes = np.asarray(sizes, dtype=np.float64)
180
+ if not sizes.flags.contiguous:
181
+ sizes = sizes.copy()
182
+ _nd_image.fourier_filter(input, sizes, n, axis, output, 1)
183
+ return output
184
+
185
+
186
+ def fourier_ellipsoid(input, size, n=-1, axis=-1, output=None):
187
+ """
188
+ Multidimensional ellipsoid Fourier filter.
189
+
190
+ The array is multiplied with the fourier transform of an ellipsoid of
191
+ given sizes.
192
+
193
+ Parameters
194
+ ----------
195
+ input : array_like
196
+ The input array.
197
+ size : float or sequence
198
+ The size of the box used for filtering.
199
+ If a float, `size` is the same for all axes. If a sequence, `size` has
200
+ to contain one value for each axis.
201
+ n : int, optional
202
+ If `n` is negative (default), then the input is assumed to be the
203
+ result of a complex fft.
204
+ If `n` is larger than or equal to zero, the input is assumed to be the
205
+ result of a real fft, and `n` gives the length of the array before
206
+ transformation along the real transform direction.
207
+ axis : int, optional
208
+ The axis of the real transform.
209
+ output : ndarray, optional
210
+ If given, the result of filtering the input is placed in this array.
211
+
212
+ Returns
213
+ -------
214
+ fourier_ellipsoid : ndarray
215
+ The filtered input.
216
+
217
+ Notes
218
+ -----
219
+ This function is implemented for arrays of rank 1, 2, or 3.
220
+
221
+ Examples
222
+ --------
223
+ >>> from scipy import ndimage, datasets
224
+ >>> import numpy.fft
225
+ >>> import matplotlib.pyplot as plt
226
+ >>> fig, (ax1, ax2) = plt.subplots(1, 2)
227
+ >>> plt.gray() # show the filtered result in grayscale
228
+ >>> ascent = datasets.ascent()
229
+ >>> input_ = numpy.fft.fft2(ascent)
230
+ >>> result = ndimage.fourier_ellipsoid(input_, size=20)
231
+ >>> result = numpy.fft.ifft2(result)
232
+ >>> ax1.imshow(ascent)
233
+ >>> ax2.imshow(result.real) # the imaginary part is an artifact
234
+ >>> plt.show()
235
+ """
236
+ input = np.asarray(input)
237
+ if input.ndim > 3:
238
+ raise NotImplementedError("Only 1d, 2d and 3d inputs are supported")
239
+ output = _get_output_fourier(output, input)
240
+ if output.size == 0:
241
+ # The C code has a bug that can result in a segfault with arrays
242
+ # that have size 0 (gh-17270), so check here.
243
+ return output
244
+ axis = normalize_axis_index(axis, input.ndim)
245
+ sizes = _ni_support._normalize_sequence(size, input.ndim)
246
+ sizes = np.asarray(sizes, dtype=np.float64)
247
+ if not sizes.flags.contiguous:
248
+ sizes = sizes.copy()
249
+ _nd_image.fourier_filter(input, sizes, n, axis, output, 2)
250
+ return output
251
+
252
+
253
+ def fourier_shift(input, shift, n=-1, axis=-1, output=None):
254
+ """
255
+ Multidimensional Fourier shift filter.
256
+
257
+ The array is multiplied with the Fourier transform of a shift operation.
258
+
259
+ Parameters
260
+ ----------
261
+ input : array_like
262
+ The input array.
263
+ shift : float or sequence
264
+ The size of the box used for filtering.
265
+ If a float, `shift` is the same for all axes. If a sequence, `shift`
266
+ has to contain one value for each axis.
267
+ n : int, optional
268
+ If `n` is negative (default), then the input is assumed to be the
269
+ result of a complex fft.
270
+ If `n` is larger than or equal to zero, the input is assumed to be the
271
+ result of a real fft, and `n` gives the length of the array before
272
+ transformation along the real transform direction.
273
+ axis : int, optional
274
+ The axis of the real transform.
275
+ output : ndarray, optional
276
+ If given, the result of shifting the input is placed in this array.
277
+
278
+ Returns
279
+ -------
280
+ fourier_shift : ndarray
281
+ The shifted input.
282
+
283
+ Examples
284
+ --------
285
+ >>> from scipy import ndimage, datasets
286
+ >>> import matplotlib.pyplot as plt
287
+ >>> import numpy.fft
288
+ >>> fig, (ax1, ax2) = plt.subplots(1, 2)
289
+ >>> plt.gray() # show the filtered result in grayscale
290
+ >>> ascent = datasets.ascent()
291
+ >>> input_ = numpy.fft.fft2(ascent)
292
+ >>> result = ndimage.fourier_shift(input_, shift=200)
293
+ >>> result = numpy.fft.ifft2(result)
294
+ >>> ax1.imshow(ascent)
295
+ >>> ax2.imshow(result.real) # the imaginary part is an artifact
296
+ >>> plt.show()
297
+ """
298
+ input = np.asarray(input)
299
+ output = _get_output_fourier_complex(output, input)
300
+ axis = normalize_axis_index(axis, input.ndim)
301
+ shifts = _ni_support._normalize_sequence(shift, input.ndim)
302
+ shifts = np.asarray(shifts, dtype=np.float64)
303
+ if not shifts.flags.contiguous:
304
+ shifts = shifts.copy()
305
+ _nd_image.fourier_shift(input, shifts, n, axis, output)
306
+ return output
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_interpolation.py ADDED
@@ -0,0 +1,1033 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2003-2005 Peter J. Verveer
2
+ #
3
+ # Redistribution and use in source and binary forms, with or without
4
+ # modification, are permitted provided that the following conditions
5
+ # are met:
6
+ #
7
+ # 1. Redistributions of source code must retain the above copyright
8
+ # notice, this list of conditions and the following disclaimer.
9
+ #
10
+ # 2. Redistributions in binary form must reproduce the above
11
+ # copyright notice, this list of conditions and the following
12
+ # disclaimer in the documentation and/or other materials provided
13
+ # with the distribution.
14
+ #
15
+ # 3. The name of the author may not be used to endorse or promote
16
+ # products derived from this software without specific prior
17
+ # written permission.
18
+ #
19
+ # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
20
+ # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21
+ # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
23
+ # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
25
+ # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
27
+ # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28
+ # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29
+ # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
+
31
+ import itertools
32
+ import warnings
33
+
34
+ import numpy as np
35
+ from scipy._lib._util import normalize_axis_index
36
+ from scipy._lib import array_api_extra as xpx
37
+
38
+ from scipy import special
39
+ from . import _ni_support
40
+ from . import _nd_image
41
+ from ._ni_docstrings import docfiller
42
+
43
+
44
+ __all__ = ['spline_filter1d', 'spline_filter', 'geometric_transform',
45
+ 'map_coordinates', 'affine_transform', 'shift', 'zoom', 'rotate']
46
+
47
+
48
+ @docfiller
49
+ def spline_filter1d(input, order=3, axis=-1, output=np.float64,
50
+ mode='mirror'):
51
+ """
52
+ Calculate a 1-D spline filter along the given axis.
53
+
54
+ The lines of the array along the given axis are filtered by a
55
+ spline filter. The order of the spline must be >= 2 and <= 5.
56
+
57
+ Parameters
58
+ ----------
59
+ %(input)s
60
+ order : int, optional
61
+ The order of the spline, default is 3.
62
+ axis : int, optional
63
+ The axis along which the spline filter is applied. Default is the last
64
+ axis.
65
+ output : ndarray or dtype, optional
66
+ The array in which to place the output, or the dtype of the returned
67
+ array. Default is ``numpy.float64``.
68
+ %(mode_interp_mirror)s
69
+
70
+ Returns
71
+ -------
72
+ spline_filter1d : ndarray
73
+ The filtered input.
74
+
75
+ See Also
76
+ --------
77
+ spline_filter : Multidimensional spline filter.
78
+
79
+ Notes
80
+ -----
81
+ All of the interpolation functions in `ndimage` do spline interpolation of
82
+ the input image. If using B-splines of `order > 1`, the input image
83
+ values have to be converted to B-spline coefficients first, which is
84
+ done by applying this 1-D filter sequentially along all
85
+ axes of the input. All functions that require B-spline coefficients
86
+ will automatically filter their inputs, a behavior controllable with
87
+ the `prefilter` keyword argument. For functions that accept a `mode`
88
+ parameter, the result will only be correct if it matches the `mode`
89
+ used when filtering.
90
+
91
+ For complex-valued `input`, this function processes the real and imaginary
92
+ components independently.
93
+
94
+ .. versionadded:: 1.6.0
95
+ Complex-valued support added.
96
+
97
+ Examples
98
+ --------
99
+ We can filter an image using 1-D spline along the given axis:
100
+
101
+ >>> from scipy.ndimage import spline_filter1d
102
+ >>> import numpy as np
103
+ >>> import matplotlib.pyplot as plt
104
+ >>> orig_img = np.eye(20) # create an image
105
+ >>> orig_img[10, :] = 1.0
106
+ >>> sp_filter_axis_0 = spline_filter1d(orig_img, axis=0)
107
+ >>> sp_filter_axis_1 = spline_filter1d(orig_img, axis=1)
108
+ >>> f, ax = plt.subplots(1, 3, sharex=True)
109
+ >>> for ind, data in enumerate([[orig_img, "original image"],
110
+ ... [sp_filter_axis_0, "spline filter (axis=0)"],
111
+ ... [sp_filter_axis_1, "spline filter (axis=1)"]]):
112
+ ... ax[ind].imshow(data[0], cmap='gray_r')
113
+ ... ax[ind].set_title(data[1])
114
+ >>> plt.tight_layout()
115
+ >>> plt.show()
116
+
117
+ """
118
+ if order < 0 or order > 5:
119
+ raise RuntimeError('spline order not supported')
120
+ input = np.asarray(input)
121
+ complex_output = np.iscomplexobj(input)
122
+ output = _ni_support._get_output(output, input,
123
+ complex_output=complex_output)
124
+ if complex_output:
125
+ spline_filter1d(input.real, order, axis, output.real, mode)
126
+ spline_filter1d(input.imag, order, axis, output.imag, mode)
127
+ return output
128
+ if order in [0, 1]:
129
+ output[...] = np.array(input)
130
+ else:
131
+ mode = _ni_support._extend_mode_to_code(mode)
132
+ axis = normalize_axis_index(axis, input.ndim)
133
+ _nd_image.spline_filter1d(input, order, axis, output, mode)
134
+ return output
135
+
136
+ @docfiller
137
+ def spline_filter(input, order=3, output=np.float64, mode='mirror'):
138
+ """
139
+ Multidimensional spline filter.
140
+
141
+ Parameters
142
+ ----------
143
+ %(input)s
144
+ order : int, optional
145
+ The order of the spline, default is 3.
146
+ output : ndarray or dtype, optional
147
+ The array in which to place the output, or the dtype of the returned
148
+ array. Default is ``numpy.float64``.
149
+ %(mode_interp_mirror)s
150
+
151
+ Returns
152
+ -------
153
+ spline_filter : ndarray
154
+ Filtered array. Has the same shape as `input`.
155
+
156
+ See Also
157
+ --------
158
+ spline_filter1d : Calculate a 1-D spline filter along the given axis.
159
+
160
+ Notes
161
+ -----
162
+ The multidimensional filter is implemented as a sequence of
163
+ 1-D spline filters. The intermediate arrays are stored
164
+ in the same data type as the output. Therefore, for output types
165
+ with a limited precision, the results may be imprecise because
166
+ intermediate results may be stored with insufficient precision.
167
+
168
+ For complex-valued `input`, this function processes the real and imaginary
169
+ components independently.
170
+
171
+ .. versionadded:: 1.6.0
172
+ Complex-valued support added.
173
+
174
+ Examples
175
+ --------
176
+ We can filter an image using multidimensional splines:
177
+
178
+ >>> from scipy.ndimage import spline_filter
179
+ >>> import numpy as np
180
+ >>> import matplotlib.pyplot as plt
181
+ >>> orig_img = np.eye(20) # create an image
182
+ >>> orig_img[10, :] = 1.0
183
+ >>> sp_filter = spline_filter(orig_img, order=3)
184
+ >>> f, ax = plt.subplots(1, 2, sharex=True)
185
+ >>> for ind, data in enumerate([[orig_img, "original image"],
186
+ ... [sp_filter, "spline filter"]]):
187
+ ... ax[ind].imshow(data[0], cmap='gray_r')
188
+ ... ax[ind].set_title(data[1])
189
+ >>> plt.tight_layout()
190
+ >>> plt.show()
191
+
192
+ """
193
+ if order < 2 or order > 5:
194
+ raise RuntimeError('spline order not supported')
195
+ input = np.asarray(input)
196
+ complex_output = np.iscomplexobj(input)
197
+ output = _ni_support._get_output(output, input,
198
+ complex_output=complex_output)
199
+ if complex_output:
200
+ spline_filter(input.real, order, output.real, mode)
201
+ spline_filter(input.imag, order, output.imag, mode)
202
+ return output
203
+ if order not in [0, 1] and input.ndim > 0:
204
+ for axis in range(input.ndim):
205
+ spline_filter1d(input, order, axis, output=output, mode=mode)
206
+ input = output
207
+ else:
208
+ output[...] = input[...]
209
+ return output
210
+
211
+
212
+ def _prepad_for_spline_filter(input, mode, cval):
213
+ if mode in ['nearest', 'grid-constant']:
214
+ npad = 12
215
+ if mode == 'grid-constant':
216
+ padded = np.pad(input, npad, mode='constant',
217
+ constant_values=cval)
218
+ elif mode == 'nearest':
219
+ padded = np.pad(input, npad, mode='edge')
220
+ else:
221
+ # other modes have exact boundary conditions implemented so
222
+ # no prepadding is needed
223
+ npad = 0
224
+ padded = input
225
+ return padded, npad
226
+
227
+
228
+ @docfiller
229
+ def geometric_transform(input, mapping, output_shape=None,
230
+ output=None, order=3,
231
+ mode='constant', cval=0.0, prefilter=True,
232
+ extra_arguments=(), extra_keywords=None):
233
+ """
234
+ Apply an arbitrary geometric transform.
235
+
236
+ The given mapping function is used to find, for each point in the
237
+ output, the corresponding coordinates in the input. The value of the
238
+ input at those coordinates is determined by spline interpolation of
239
+ the requested order.
240
+
241
+ Parameters
242
+ ----------
243
+ %(input)s
244
+ mapping : {callable, scipy.LowLevelCallable}
245
+ A callable object that accepts a tuple of length equal to the output
246
+ array rank, and returns the corresponding input coordinates as a tuple
247
+ of length equal to the input array rank.
248
+ output_shape : tuple of ints, optional
249
+ Shape tuple.
250
+ %(output)s
251
+ order : int, optional
252
+ The order of the spline interpolation, default is 3.
253
+ The order has to be in the range 0-5.
254
+ %(mode_interp_constant)s
255
+ %(cval)s
256
+ %(prefilter)s
257
+ extra_arguments : tuple, optional
258
+ Extra arguments passed to `mapping`.
259
+ extra_keywords : dict, optional
260
+ Extra keywords passed to `mapping`.
261
+
262
+ Returns
263
+ -------
264
+ output : ndarray
265
+ The filtered input.
266
+
267
+ See Also
268
+ --------
269
+ map_coordinates, affine_transform, spline_filter1d
270
+
271
+
272
+ Notes
273
+ -----
274
+ This function also accepts low-level callback functions with one
275
+ the following signatures and wrapped in `scipy.LowLevelCallable`:
276
+
277
+ .. code:: c
278
+
279
+ int mapping(npy_intp *output_coordinates, double *input_coordinates,
280
+ int output_rank, int input_rank, void *user_data)
281
+ int mapping(intptr_t *output_coordinates, double *input_coordinates,
282
+ int output_rank, int input_rank, void *user_data)
283
+
284
+ The calling function iterates over the elements of the output array,
285
+ calling the callback function at each element. The coordinates of the
286
+ current output element are passed through ``output_coordinates``. The
287
+ callback function must return the coordinates at which the input must
288
+ be interpolated in ``input_coordinates``. The rank of the input and
289
+ output arrays are given by ``input_rank`` and ``output_rank``
290
+ respectively. ``user_data`` is the data pointer provided
291
+ to `scipy.LowLevelCallable` as-is.
292
+
293
+ The callback function must return an integer error status that is zero
294
+ if something went wrong and one otherwise. If an error occurs, you should
295
+ normally set the Python error status with an informative message
296
+ before returning, otherwise a default error message is set by the
297
+ calling function.
298
+
299
+ In addition, some other low-level function pointer specifications
300
+ are accepted, but these are for backward compatibility only and should
301
+ not be used in new code.
302
+
303
+ For complex-valued `input`, this function transforms the real and imaginary
304
+ components independently.
305
+
306
+ .. versionadded:: 1.6.0
307
+ Complex-valued support added.
308
+
309
+ Examples
310
+ --------
311
+ >>> import numpy as np
312
+ >>> from scipy.ndimage import geometric_transform
313
+ >>> a = np.arange(12.).reshape((4, 3))
314
+ >>> def shift_func(output_coords):
315
+ ... return (output_coords[0] - 0.5, output_coords[1] - 0.5)
316
+ ...
317
+ >>> geometric_transform(a, shift_func)
318
+ array([[ 0. , 0. , 0. ],
319
+ [ 0. , 1.362, 2.738],
320
+ [ 0. , 4.812, 6.187],
321
+ [ 0. , 8.263, 9.637]])
322
+
323
+ >>> b = [1, 2, 3, 4, 5]
324
+ >>> def shift_func(output_coords):
325
+ ... return (output_coords[0] - 3,)
326
+ ...
327
+ >>> geometric_transform(b, shift_func, mode='constant')
328
+ array([0, 0, 0, 1, 2])
329
+ >>> geometric_transform(b, shift_func, mode='nearest')
330
+ array([1, 1, 1, 1, 2])
331
+ >>> geometric_transform(b, shift_func, mode='reflect')
332
+ array([3, 2, 1, 1, 2])
333
+ >>> geometric_transform(b, shift_func, mode='wrap')
334
+ array([2, 3, 4, 1, 2])
335
+
336
+ """
337
+ if extra_keywords is None:
338
+ extra_keywords = {}
339
+ if order < 0 or order > 5:
340
+ raise RuntimeError('spline order not supported')
341
+ input = np.asarray(input)
342
+ if output_shape is None:
343
+ output_shape = input.shape
344
+ if input.ndim < 1 or len(output_shape) < 1:
345
+ raise RuntimeError('input and output rank must be > 0')
346
+ complex_output = np.iscomplexobj(input)
347
+ output = _ni_support._get_output(output, input, shape=output_shape,
348
+ complex_output=complex_output)
349
+ if complex_output:
350
+ kwargs = dict(order=order, mode=mode, prefilter=prefilter,
351
+ output_shape=output_shape,
352
+ extra_arguments=extra_arguments,
353
+ extra_keywords=extra_keywords)
354
+ geometric_transform(input.real, mapping, output=output.real,
355
+ cval=np.real(cval), **kwargs)
356
+ geometric_transform(input.imag, mapping, output=output.imag,
357
+ cval=np.imag(cval), **kwargs)
358
+ return output
359
+
360
+ if prefilter and order > 1:
361
+ padded, npad = _prepad_for_spline_filter(input, mode, cval)
362
+ filtered = spline_filter(padded, order, output=np.float64,
363
+ mode=mode)
364
+ else:
365
+ npad = 0
366
+ filtered = input
367
+ mode = _ni_support._extend_mode_to_code(mode)
368
+ _nd_image.geometric_transform(filtered, mapping, None, None, None, output,
369
+ order, mode, cval, npad, extra_arguments,
370
+ extra_keywords)
371
+ return output
372
+
373
+
374
+ @docfiller
375
+ def map_coordinates(input, coordinates, output=None, order=3,
376
+ mode='constant', cval=0.0, prefilter=True):
377
+ """
378
+ Map the input array to new coordinates by interpolation.
379
+
380
+ The array of coordinates is used to find, for each point in the output,
381
+ the corresponding coordinates in the input. The value of the input at
382
+ those coordinates is determined by spline interpolation of the
383
+ requested order.
384
+
385
+ The shape of the output is derived from that of the coordinate
386
+ array by dropping the first axis. The values of the array along
387
+ the first axis are the coordinates in the input array at which the
388
+ output value is found.
389
+
390
+ Parameters
391
+ ----------
392
+ %(input)s
393
+ coordinates : array_like
394
+ The coordinates at which `input` is evaluated.
395
+ %(output)s
396
+ order : int, optional
397
+ The order of the spline interpolation, default is 3.
398
+ The order has to be in the range 0-5.
399
+ %(mode_interp_constant)s
400
+ %(cval)s
401
+ %(prefilter)s
402
+
403
+ Returns
404
+ -------
405
+ map_coordinates : ndarray
406
+ The result of transforming the input. The shape of the output is
407
+ derived from that of `coordinates` by dropping the first axis.
408
+
409
+ See Also
410
+ --------
411
+ spline_filter, geometric_transform, scipy.interpolate
412
+
413
+ Notes
414
+ -----
415
+ For complex-valued `input`, this function maps the real and imaginary
416
+ components independently.
417
+
418
+ .. versionadded:: 1.6.0
419
+ Complex-valued support added.
420
+
421
+ Examples
422
+ --------
423
+ >>> from scipy import ndimage
424
+ >>> import numpy as np
425
+ >>> a = np.arange(12.).reshape((4, 3))
426
+ >>> a
427
+ array([[ 0., 1., 2.],
428
+ [ 3., 4., 5.],
429
+ [ 6., 7., 8.],
430
+ [ 9., 10., 11.]])
431
+ >>> ndimage.map_coordinates(a, [[0.5, 2], [0.5, 1]], order=1)
432
+ array([ 2., 7.])
433
+
434
+ Above, the interpolated value of a[0.5, 0.5] gives output[0], while
435
+ a[2, 1] is output[1].
436
+
437
+ >>> inds = np.array([[0.5, 2], [0.5, 4]])
438
+ >>> ndimage.map_coordinates(a, inds, order=1, cval=-33.3)
439
+ array([ 2. , -33.3])
440
+ >>> ndimage.map_coordinates(a, inds, order=1, mode='nearest')
441
+ array([ 2., 8.])
442
+ >>> ndimage.map_coordinates(a, inds, order=1, cval=0, output=bool)
443
+ array([ True, False], dtype=bool)
444
+
445
+ """
446
+ if order < 0 or order > 5:
447
+ raise RuntimeError('spline order not supported')
448
+ input = np.asarray(input)
449
+ coordinates = np.asarray(coordinates)
450
+ if np.iscomplexobj(coordinates):
451
+ raise TypeError('Complex type not supported')
452
+ output_shape = coordinates.shape[1:]
453
+ if input.ndim < 1 or len(output_shape) < 1:
454
+ raise RuntimeError('input and output rank must be > 0')
455
+ if coordinates.shape[0] != input.ndim:
456
+ raise RuntimeError('invalid shape for coordinate array')
457
+ complex_output = np.iscomplexobj(input)
458
+ output = _ni_support._get_output(output, input, shape=output_shape,
459
+ complex_output=complex_output)
460
+ if complex_output:
461
+ kwargs = dict(order=order, mode=mode, prefilter=prefilter)
462
+ map_coordinates(input.real, coordinates, output=output.real,
463
+ cval=np.real(cval), **kwargs)
464
+ map_coordinates(input.imag, coordinates, output=output.imag,
465
+ cval=np.imag(cval), **kwargs)
466
+ return output
467
+ if prefilter and order > 1:
468
+ padded, npad = _prepad_for_spline_filter(input, mode, cval)
469
+ filtered = spline_filter(padded, order, output=np.float64, mode=mode)
470
+ else:
471
+ npad = 0
472
+ filtered = input
473
+ mode = _ni_support._extend_mode_to_code(mode)
474
+ _nd_image.geometric_transform(filtered, None, coordinates, None, None,
475
+ output, order, mode, cval, npad, None, None)
476
+ return output
477
+
478
+
479
+ @docfiller
480
+ def affine_transform(input, matrix, offset=0.0, output_shape=None,
481
+ output=None, order=3,
482
+ mode='constant', cval=0.0, prefilter=True):
483
+ """
484
+ Apply an affine transformation.
485
+
486
+ Given an output image pixel index vector ``o``, the pixel value
487
+ is determined from the input image at position
488
+ ``np.dot(matrix, o) + offset``.
489
+
490
+ This does 'pull' (or 'backward') resampling, transforming the output space
491
+ to the input to locate data. Affine transformations are often described in
492
+ the 'push' (or 'forward') direction, transforming input to output. If you
493
+ have a matrix for the 'push' transformation, use its inverse
494
+ (:func:`numpy.linalg.inv`) in this function.
495
+
496
+ Parameters
497
+ ----------
498
+ %(input)s
499
+ matrix : ndarray
500
+ The inverse coordinate transformation matrix, mapping output
501
+ coordinates to input coordinates. If ``ndim`` is the number of
502
+ dimensions of ``input``, the given matrix must have one of the
503
+ following shapes:
504
+
505
+ - ``(ndim, ndim)``: the linear transformation matrix for each
506
+ output coordinate.
507
+ - ``(ndim,)``: assume that the 2-D transformation matrix is
508
+ diagonal, with the diagonal specified by the given value. A more
509
+ efficient algorithm is then used that exploits the separability
510
+ of the problem.
511
+ - ``(ndim + 1, ndim + 1)``: assume that the transformation is
512
+ specified using homogeneous coordinates [1]_. In this case, any
513
+ value passed to ``offset`` is ignored.
514
+ - ``(ndim, ndim + 1)``: as above, but the bottom row of a
515
+ homogeneous transformation matrix is always ``[0, 0, ..., 1]``,
516
+ and may be omitted.
517
+
518
+ offset : float or sequence, optional
519
+ The offset into the array where the transform is applied. If a float,
520
+ `offset` is the same for each axis. If a sequence, `offset` should
521
+ contain one value for each axis.
522
+ output_shape : tuple of ints, optional
523
+ Shape tuple.
524
+ %(output)s
525
+ order : int, optional
526
+ The order of the spline interpolation, default is 3.
527
+ The order has to be in the range 0-5.
528
+ %(mode_interp_constant)s
529
+ %(cval)s
530
+ %(prefilter)s
531
+
532
+ Returns
533
+ -------
534
+ affine_transform : ndarray
535
+ The transformed input.
536
+
537
+ Examples
538
+ --------
539
+ Use `affine_transform` to stretch an image::
540
+
541
+ >>> from scipy.ndimage import affine_transform
542
+ >>> from scipy.datasets import face
543
+ >>> from matplotlib import pyplot as plt
544
+ >>> import numpy as np
545
+ >>> im = face(gray=True)
546
+ >>> matrix = (0.5, 2)
547
+ >>> im2 = affine_transform(im, matrix)
548
+ >>> plt.imshow(im2)
549
+ >>> plt.show()
550
+
551
+ Rotate an image by 90 degrees and project it onto an expanded canvas::
552
+
553
+ >>> matrix = ((0, 1), (1, 0))
554
+ >>> im3 = affine_transform(im, matrix, output_shape=(1024, 1024))
555
+ >>> plt.imshow(im3)
556
+ >>> plt.show()
557
+
558
+ Offset the rotation so that the image is centred::
559
+
560
+ >>> output_shape = (1200, 1200)
561
+ >>> offset = (np.array(im.shape) - output_shape) / 2
562
+ >>> im4 = affine_transform(im, matrix, offset=offset, output_shape=output_shape)
563
+ >>> plt.imshow(im4)
564
+ >>> plt.show()
565
+
566
+ Notes
567
+ -----
568
+ The given matrix and offset are used to find for each point in the
569
+ output the corresponding coordinates in the input by an affine
570
+ transformation. The value of the input at those coordinates is
571
+ determined by spline interpolation of the requested order. Points
572
+ outside the boundaries of the input are filled according to the given
573
+ mode.
574
+
575
+ .. versionchanged:: 0.18.0
576
+ Previously, the exact interpretation of the affine transformation
577
+ depended on whether the matrix was supplied as a 1-D or a
578
+ 2-D array. If a 1-D array was supplied
579
+ to the matrix parameter, the output pixel value at index ``o``
580
+ was determined from the input image at position
581
+ ``matrix * (o + offset)``.
582
+
583
+ For complex-valued `input`, this function transforms the real and imaginary
584
+ components independently.
585
+
586
+ .. versionadded:: 1.6.0
587
+ Complex-valued support added.
588
+
589
+ References
590
+ ----------
591
+ .. [1] https://en.wikipedia.org/wiki/Homogeneous_coordinates
592
+ """
593
+ if order < 0 or order > 5:
594
+ raise RuntimeError('spline order not supported')
595
+ input = np.asarray(input)
596
+ if output_shape is None:
597
+ if isinstance(output, np.ndarray):
598
+ output_shape = output.shape
599
+ else:
600
+ output_shape = input.shape
601
+ if input.ndim < 1 or len(output_shape) < 1:
602
+ raise RuntimeError('input and output rank must be > 0')
603
+ complex_output = np.iscomplexobj(input)
604
+ output = _ni_support._get_output(output, input, shape=output_shape,
605
+ complex_output=complex_output)
606
+ if complex_output:
607
+ kwargs = dict(offset=offset, output_shape=output_shape, order=order,
608
+ mode=mode, prefilter=prefilter)
609
+ affine_transform(input.real, matrix, output=output.real,
610
+ cval=np.real(cval), **kwargs)
611
+ affine_transform(input.imag, matrix, output=output.imag,
612
+ cval=np.imag(cval), **kwargs)
613
+ return output
614
+ if prefilter and order > 1:
615
+ padded, npad = _prepad_for_spline_filter(input, mode, cval)
616
+ filtered = spline_filter(padded, order, output=np.float64, mode=mode)
617
+ else:
618
+ npad = 0
619
+ filtered = input
620
+ mode = _ni_support._extend_mode_to_code(mode)
621
+ matrix = np.asarray(matrix, dtype=np.float64)
622
+ if matrix.ndim not in [1, 2] or matrix.shape[0] < 1:
623
+ raise RuntimeError('no proper affine matrix provided')
624
+ if (matrix.ndim == 2 and matrix.shape[1] == input.ndim + 1 and
625
+ (matrix.shape[0] in [input.ndim, input.ndim + 1])):
626
+ if matrix.shape[0] == input.ndim + 1:
627
+ exptd = [0] * input.ndim + [1]
628
+ if not np.all(matrix[input.ndim] == exptd):
629
+ msg = (f'Expected homogeneous transformation matrix with '
630
+ f'shape {matrix.shape} for image shape {input.shape}, '
631
+ f'but bottom row was not equal to {exptd}')
632
+ raise ValueError(msg)
633
+ # assume input is homogeneous coordinate transformation matrix
634
+ offset = matrix[:input.ndim, input.ndim]
635
+ matrix = matrix[:input.ndim, :input.ndim]
636
+ if matrix.shape[0] != input.ndim:
637
+ raise RuntimeError('affine matrix has wrong number of rows')
638
+ if matrix.ndim == 2 and matrix.shape[1] != output.ndim:
639
+ raise RuntimeError('affine matrix has wrong number of columns')
640
+ if not matrix.flags.contiguous:
641
+ matrix = matrix.copy()
642
+ offset = _ni_support._normalize_sequence(offset, input.ndim)
643
+ offset = np.asarray(offset, dtype=np.float64)
644
+ if offset.ndim != 1 or offset.shape[0] < 1:
645
+ raise RuntimeError('no proper offset provided')
646
+ if not offset.flags.contiguous:
647
+ offset = offset.copy()
648
+ if matrix.ndim == 1:
649
+ _nd_image.zoom_shift(filtered, matrix, offset/matrix, output, order,
650
+ mode, cval, npad, False)
651
+ else:
652
+ _nd_image.geometric_transform(filtered, None, None, matrix, offset,
653
+ output, order, mode, cval, npad, None,
654
+ None)
655
+ return output
656
+
657
+
658
+ @docfiller
659
+ def shift(input, shift, output=None, order=3, mode='constant', cval=0.0,
660
+ prefilter=True):
661
+ """
662
+ Shift an array.
663
+
664
+ The array is shifted using spline interpolation of the requested order.
665
+ Points outside the boundaries of the input are filled according to the
666
+ given mode.
667
+
668
+ Parameters
669
+ ----------
670
+ %(input)s
671
+ shift : float or sequence
672
+ The shift along the axes. If a float, `shift` is the same for each
673
+ axis. If a sequence, `shift` should contain one value for each axis.
674
+ %(output)s
675
+ order : int, optional
676
+ The order of the spline interpolation, default is 3.
677
+ The order has to be in the range 0-5.
678
+ %(mode_interp_constant)s
679
+ %(cval)s
680
+ %(prefilter)s
681
+
682
+ Returns
683
+ -------
684
+ shift : ndarray
685
+ The shifted input.
686
+
687
+ See Also
688
+ --------
689
+ affine_transform : Affine transformations
690
+
691
+ Notes
692
+ -----
693
+ For complex-valued `input`, this function shifts the real and imaginary
694
+ components independently.
695
+
696
+ .. versionadded:: 1.6.0
697
+ Complex-valued support added.
698
+
699
+ Examples
700
+ --------
701
+ Import the necessary modules and an exemplary image.
702
+
703
+ >>> from scipy.ndimage import shift
704
+ >>> import matplotlib.pyplot as plt
705
+ >>> from scipy import datasets
706
+ >>> image = datasets.ascent()
707
+
708
+ Shift the image vertically by 20 pixels.
709
+
710
+ >>> image_shifted_vertically = shift(image, (20, 0))
711
+
712
+ Shift the image vertically by -200 pixels and horizontally by 100 pixels.
713
+
714
+ >>> image_shifted_both_directions = shift(image, (-200, 100))
715
+
716
+ Plot the original and the shifted images.
717
+
718
+ >>> fig, axes = plt.subplots(3, 1, figsize=(4, 12))
719
+ >>> plt.gray() # show the filtered result in grayscale
720
+ >>> top, middle, bottom = axes
721
+ >>> for ax in axes:
722
+ ... ax.set_axis_off() # remove coordinate system
723
+ >>> top.imshow(image)
724
+ >>> top.set_title("Original image")
725
+ >>> middle.imshow(image_shifted_vertically)
726
+ >>> middle.set_title("Vertically shifted image")
727
+ >>> bottom.imshow(image_shifted_both_directions)
728
+ >>> bottom.set_title("Image shifted in both directions")
729
+ >>> fig.tight_layout()
730
+ """
731
+ if order < 0 or order > 5:
732
+ raise RuntimeError('spline order not supported')
733
+ input = np.asarray(input)
734
+ if input.ndim < 1:
735
+ raise RuntimeError('input and output rank must be > 0')
736
+ complex_output = np.iscomplexobj(input)
737
+ output = _ni_support._get_output(output, input, complex_output=complex_output)
738
+ if complex_output:
739
+ # import under different name to avoid confusion with shift parameter
740
+ from scipy.ndimage._interpolation import shift as _shift
741
+
742
+ kwargs = dict(order=order, mode=mode, prefilter=prefilter)
743
+ _shift(input.real, shift, output=output.real, cval=np.real(cval), **kwargs)
744
+ _shift(input.imag, shift, output=output.imag, cval=np.imag(cval), **kwargs)
745
+ return output
746
+ if prefilter and order > 1:
747
+ padded, npad = _prepad_for_spline_filter(input, mode, cval)
748
+ filtered = spline_filter(padded, order, output=np.float64, mode=mode)
749
+ else:
750
+ npad = 0
751
+ filtered = input
752
+ mode = _ni_support._extend_mode_to_code(mode)
753
+ shift = _ni_support._normalize_sequence(shift, input.ndim)
754
+ shift = [-ii for ii in shift]
755
+ shift = np.asarray(shift, dtype=np.float64)
756
+ if not shift.flags.contiguous:
757
+ shift = shift.copy()
758
+ _nd_image.zoom_shift(filtered, None, shift, output, order, mode, cval,
759
+ npad, False)
760
+ return output
761
+
762
+
763
+ @docfiller
764
+ def zoom(input, zoom, output=None, order=3, mode='constant', cval=0.0,
765
+ prefilter=True, *, grid_mode=False):
766
+ """
767
+ Zoom an array.
768
+
769
+ The array is zoomed using spline interpolation of the requested order.
770
+
771
+ Parameters
772
+ ----------
773
+ %(input)s
774
+ zoom : float or sequence
775
+ The zoom factor along the axes. If a float, `zoom` is the same for each
776
+ axis. If a sequence, `zoom` should contain one value for each axis.
777
+ %(output)s
778
+ order : int, optional
779
+ The order of the spline interpolation, default is 3.
780
+ The order has to be in the range 0-5.
781
+ %(mode_interp_constant)s
782
+ %(cval)s
783
+ %(prefilter)s
784
+ grid_mode : bool, optional
785
+ If False, the distance from the pixel centers is zoomed. Otherwise, the
786
+ distance including the full pixel extent is used. For example, a 1d
787
+ signal of length 5 is considered to have length 4 when `grid_mode` is
788
+ False, but length 5 when `grid_mode` is True. See the following
789
+ visual illustration:
790
+
791
+ .. code-block:: text
792
+
793
+ | pixel 1 | pixel 2 | pixel 3 | pixel 4 | pixel 5 |
794
+ |<-------------------------------------->|
795
+ vs.
796
+ |<----------------------------------------------->|
797
+
798
+ The starting point of the arrow in the diagram above corresponds to
799
+ coordinate location 0 in each mode.
800
+
801
+ Returns
802
+ -------
803
+ zoom : ndarray
804
+ The zoomed input.
805
+
806
+ Notes
807
+ -----
808
+ For complex-valued `input`, this function zooms the real and imaginary
809
+ components independently.
810
+
811
+ .. versionadded:: 1.6.0
812
+ Complex-valued support added.
813
+
814
+ Examples
815
+ --------
816
+ >>> from scipy import ndimage, datasets
817
+ >>> import matplotlib.pyplot as plt
818
+
819
+ >>> fig = plt.figure()
820
+ >>> ax1 = fig.add_subplot(121) # left side
821
+ >>> ax2 = fig.add_subplot(122) # right side
822
+ >>> ascent = datasets.ascent()
823
+ >>> result = ndimage.zoom(ascent, 3.0)
824
+ >>> ax1.imshow(ascent, vmin=0, vmax=255)
825
+ >>> ax2.imshow(result, vmin=0, vmax=255)
826
+ >>> plt.show()
827
+
828
+ >>> print(ascent.shape)
829
+ (512, 512)
830
+
831
+ >>> print(result.shape)
832
+ (1536, 1536)
833
+ """
834
+ if order < 0 or order > 5:
835
+ raise RuntimeError('spline order not supported')
836
+ input = np.asarray(input)
837
+ if input.ndim < 1:
838
+ raise RuntimeError('input and output rank must be > 0')
839
+ zoom = _ni_support._normalize_sequence(zoom, input.ndim)
840
+ output_shape = tuple(
841
+ [int(round(ii * jj)) for ii, jj in zip(input.shape, zoom)])
842
+ complex_output = np.iscomplexobj(input)
843
+ output = _ni_support._get_output(output, input, shape=output_shape,
844
+ complex_output=complex_output)
845
+ if all(z == 1 for z in zoom) and prefilter: # early exit for gh-20999
846
+ # zoom 1 means "return original image". If `prefilter=False`,
847
+ # `input` is *not* the original image; processing is still needed
848
+ # to undo the filter. So we only early exit if `prefilter`.
849
+ output = xpx.at(output)[...].set(input)
850
+ return output
851
+ if complex_output:
852
+ # import under different name to avoid confusion with zoom parameter
853
+ from scipy.ndimage._interpolation import zoom as _zoom
854
+
855
+ kwargs = dict(order=order, mode=mode, prefilter=prefilter)
856
+ _zoom(input.real, zoom, output=output.real, cval=np.real(cval), **kwargs)
857
+ _zoom(input.imag, zoom, output=output.imag, cval=np.imag(cval), **kwargs)
858
+ return output
859
+ if prefilter and order > 1:
860
+ padded, npad = _prepad_for_spline_filter(input, mode, cval)
861
+ filtered = spline_filter(padded, order, output=np.float64, mode=mode)
862
+ else:
863
+ npad = 0
864
+ filtered = input
865
+ if grid_mode:
866
+ # warn about modes that may have surprising behavior
867
+ suggest_mode = None
868
+ if mode == 'constant':
869
+ suggest_mode = 'grid-constant'
870
+ elif mode == 'wrap':
871
+ suggest_mode = 'grid-wrap'
872
+ if suggest_mode is not None:
873
+ warnings.warn(
874
+ (f"It is recommended to use mode = {suggest_mode} instead of {mode} "
875
+ f"when grid_mode is True."),
876
+ stacklevel=2
877
+ )
878
+ mode = _ni_support._extend_mode_to_code(mode)
879
+
880
+ zoom_div = np.array(output_shape)
881
+ zoom_nominator = np.array(input.shape)
882
+ if not grid_mode:
883
+ zoom_div -= 1
884
+ zoom_nominator -= 1
885
+
886
+ # Zooming to infinite values is unpredictable, so just choose
887
+ # zoom factor 1 instead
888
+ zoom = np.divide(zoom_nominator, zoom_div,
889
+ out=np.ones_like(input.shape, dtype=np.float64),
890
+ where=zoom_div != 0)
891
+ zoom = np.ascontiguousarray(zoom)
892
+ _nd_image.zoom_shift(filtered, zoom, None, output, order, mode, cval, npad,
893
+ grid_mode)
894
+ return output
895
+
896
+
897
+ @docfiller
898
+ def rotate(input, angle, axes=(1, 0), reshape=True, output=None, order=3,
899
+ mode='constant', cval=0.0, prefilter=True):
900
+ """
901
+ Rotate an array.
902
+
903
+ The array is rotated in the plane defined by the two axes given by the
904
+ `axes` parameter using spline interpolation of the requested order.
905
+
906
+ Parameters
907
+ ----------
908
+ %(input)s
909
+ angle : float
910
+ The rotation angle in degrees.
911
+ axes : tuple of 2 ints, optional
912
+ The two axes that define the plane of rotation. Default is the first
913
+ two axes.
914
+ reshape : bool, optional
915
+ If `reshape` is true, the output shape is adapted so that the input
916
+ array is contained completely in the output. Default is True.
917
+ %(output)s
918
+ order : int, optional
919
+ The order of the spline interpolation, default is 3.
920
+ The order has to be in the range 0-5.
921
+ %(mode_interp_constant)s
922
+ %(cval)s
923
+ %(prefilter)s
924
+
925
+ Returns
926
+ -------
927
+ rotate : ndarray
928
+ The rotated input.
929
+
930
+ Notes
931
+ -----
932
+ For complex-valued `input`, this function rotates the real and imaginary
933
+ components independently.
934
+
935
+ .. versionadded:: 1.6.0
936
+ Complex-valued support added.
937
+
938
+ Examples
939
+ --------
940
+ >>> from scipy import ndimage, datasets
941
+ >>> import matplotlib.pyplot as plt
942
+ >>> fig = plt.figure(figsize=(10, 3))
943
+ >>> ax1, ax2, ax3 = fig.subplots(1, 3)
944
+ >>> img = datasets.ascent()
945
+ >>> img_45 = ndimage.rotate(img, 45, reshape=False)
946
+ >>> full_img_45 = ndimage.rotate(img, 45, reshape=True)
947
+ >>> ax1.imshow(img, cmap='gray')
948
+ >>> ax1.set_axis_off()
949
+ >>> ax2.imshow(img_45, cmap='gray')
950
+ >>> ax2.set_axis_off()
951
+ >>> ax3.imshow(full_img_45, cmap='gray')
952
+ >>> ax3.set_axis_off()
953
+ >>> fig.set_layout_engine('tight')
954
+ >>> plt.show()
955
+ >>> print(img.shape)
956
+ (512, 512)
957
+ >>> print(img_45.shape)
958
+ (512, 512)
959
+ >>> print(full_img_45.shape)
960
+ (724, 724)
961
+
962
+ """
963
+ input_arr = np.asarray(input)
964
+ ndim = input_arr.ndim
965
+
966
+ if ndim < 2:
967
+ raise ValueError('input array should be at least 2D')
968
+
969
+ axes = list(axes)
970
+
971
+ if len(axes) != 2:
972
+ raise ValueError('axes should contain exactly two values')
973
+
974
+ if not all([float(ax).is_integer() for ax in axes]):
975
+ raise ValueError('axes should contain only integer values')
976
+
977
+ if axes[0] < 0:
978
+ axes[0] += ndim
979
+ if axes[1] < 0:
980
+ axes[1] += ndim
981
+ if axes[0] < 0 or axes[1] < 0 or axes[0] >= ndim or axes[1] >= ndim:
982
+ raise ValueError('invalid rotation plane specified')
983
+
984
+ axes.sort()
985
+
986
+ c, s = special.cosdg(angle), special.sindg(angle)
987
+
988
+ rot_matrix = np.array([[c, s],
989
+ [-s, c]])
990
+
991
+ img_shape = np.asarray(input_arr.shape)
992
+ in_plane_shape = img_shape[axes]
993
+ if reshape:
994
+ # Compute transformed input bounds
995
+ iy, ix = in_plane_shape
996
+ out_bounds = rot_matrix @ [[0, 0, iy, iy],
997
+ [0, ix, 0, ix]]
998
+ # Compute the shape of the transformed input plane
999
+ out_plane_shape = (np.ptp(out_bounds, axis=1) + 0.5).astype(int)
1000
+ else:
1001
+ out_plane_shape = img_shape[axes]
1002
+
1003
+ out_center = rot_matrix @ ((out_plane_shape - 1) / 2)
1004
+ in_center = (in_plane_shape - 1) / 2
1005
+ offset = in_center - out_center
1006
+
1007
+ output_shape = img_shape
1008
+ output_shape[axes] = out_plane_shape
1009
+ output_shape = tuple(output_shape)
1010
+
1011
+ complex_output = np.iscomplexobj(input_arr)
1012
+ output = _ni_support._get_output(output, input_arr, shape=output_shape,
1013
+ complex_output=complex_output)
1014
+
1015
+ if ndim <= 2:
1016
+ affine_transform(input_arr, rot_matrix, offset, output_shape, output,
1017
+ order, mode, cval, prefilter)
1018
+ else:
1019
+ # If ndim > 2, the rotation is applied over all the planes
1020
+ # parallel to axes
1021
+ planes_coord = itertools.product(
1022
+ *[[slice(None)] if ax in axes else range(img_shape[ax])
1023
+ for ax in range(ndim)])
1024
+
1025
+ out_plane_shape = tuple(out_plane_shape)
1026
+
1027
+ for coordinates in planes_coord:
1028
+ ia = input_arr[coordinates]
1029
+ oa = output[coordinates]
1030
+ affine_transform(ia, rot_matrix, offset, out_plane_shape,
1031
+ oa, order, mode, cval, prefilter)
1032
+
1033
+ return output
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_measurements.py ADDED
@@ -0,0 +1,1689 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2003-2005 Peter J. Verveer
2
+ #
3
+ # Redistribution and use in source and binary forms, with or without
4
+ # modification, are permitted provided that the following conditions
5
+ # are met:
6
+ #
7
+ # 1. Redistributions of source code must retain the above copyright
8
+ # notice, this list of conditions and the following disclaimer.
9
+ #
10
+ # 2. Redistributions in binary form must reproduce the above
11
+ # copyright notice, this list of conditions and the following
12
+ # disclaimer in the documentation and/or other materials provided
13
+ # with the distribution.
14
+ #
15
+ # 3. The name of the author may not be used to endorse or promote
16
+ # products derived from this software without specific prior
17
+ # written permission.
18
+ #
19
+ # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
20
+ # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21
+ # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
23
+ # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
25
+ # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
27
+ # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28
+ # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29
+ # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
+
31
+ import numpy as np
32
+ from . import _ni_support
33
+ from . import _ni_label
34
+ from . import _nd_image
35
+ from . import _morphology
36
+
37
+ __all__ = ['label', 'find_objects', 'labeled_comprehension', 'sum', 'mean',
38
+ 'variance', 'standard_deviation', 'minimum', 'maximum', 'median',
39
+ 'minimum_position', 'maximum_position', 'extrema', 'center_of_mass',
40
+ 'histogram', 'watershed_ift', 'sum_labels', 'value_indices']
41
+
42
+
43
+ def label(input, structure=None, output=None):
44
+ """
45
+ Label features in an array.
46
+
47
+ Parameters
48
+ ----------
49
+ input : array_like
50
+ An array-like object to be labeled. Any non-zero values in `input` are
51
+ counted as features and zero values are considered the background.
52
+ structure : array_like, optional
53
+ A structuring element that defines feature connections.
54
+ `structure` must be centrosymmetric
55
+ (see Notes).
56
+ If no structuring element is provided,
57
+ one is automatically generated with a squared connectivity equal to
58
+ one. That is, for a 2-D `input` array, the default structuring element
59
+ is::
60
+
61
+ [[0,1,0],
62
+ [1,1,1],
63
+ [0,1,0]]
64
+
65
+ output : (None, data-type, array_like), optional
66
+ If `output` is a data type, it specifies the type of the resulting
67
+ labeled feature array.
68
+ If `output` is an array-like object, then `output` will be updated
69
+ with the labeled features from this function. This function can
70
+ operate in-place, by passing output=input.
71
+ Note that the output must be able to store the largest label, or this
72
+ function will raise an Exception.
73
+
74
+ Returns
75
+ -------
76
+ label : ndarray or int
77
+ An integer ndarray where each unique feature in `input` has a unique
78
+ label in the returned array.
79
+ num_features : int
80
+ How many objects were found.
81
+
82
+ If `output` is None, this function returns a tuple of
83
+ (`labeled_array`, `num_features`).
84
+
85
+ If `output` is a ndarray, then it will be updated with values in
86
+ `labeled_array` and only `num_features` will be returned by this
87
+ function.
88
+
89
+ See Also
90
+ --------
91
+ find_objects : generate a list of slices for the labeled features (or
92
+ objects); useful for finding features' position or
93
+ dimensions
94
+
95
+ Notes
96
+ -----
97
+ A centrosymmetric matrix is a matrix that is symmetric about the center.
98
+ See [1]_ for more information.
99
+
100
+ The `structure` matrix must be centrosymmetric to ensure
101
+ two-way connections.
102
+ For instance, if the `structure` matrix is not centrosymmetric
103
+ and is defined as::
104
+
105
+ [[0,1,0],
106
+ [1,1,0],
107
+ [0,0,0]]
108
+
109
+ and the `input` is::
110
+
111
+ [[1,2],
112
+ [0,3]]
113
+
114
+ then the structure matrix would indicate the
115
+ entry 2 in the input is connected to 1,
116
+ but 1 is not connected to 2.
117
+
118
+ References
119
+ ----------
120
+ .. [1] James R. Weaver, "Centrosymmetric (cross-symmetric)
121
+ matrices, their basic properties, eigenvalues, and
122
+ eigenvectors." The American Mathematical Monthly 92.10
123
+ (1985): 711-717.
124
+
125
+ Examples
126
+ --------
127
+ Create an image with some features, then label it using the default
128
+ (cross-shaped) structuring element:
129
+
130
+ >>> from scipy.ndimage import label, generate_binary_structure
131
+ >>> import numpy as np
132
+ >>> a = np.array([[0,0,1,1,0,0],
133
+ ... [0,0,0,1,0,0],
134
+ ... [1,1,0,0,1,0],
135
+ ... [0,0,0,1,0,0]])
136
+ >>> labeled_array, num_features = label(a)
137
+
138
+ Each of the 4 features are labeled with a different integer:
139
+
140
+ >>> num_features
141
+ 4
142
+ >>> labeled_array
143
+ array([[0, 0, 1, 1, 0, 0],
144
+ [0, 0, 0, 1, 0, 0],
145
+ [2, 2, 0, 0, 3, 0],
146
+ [0, 0, 0, 4, 0, 0]], dtype=int32)
147
+
148
+ Generate a structuring element that will consider features connected even
149
+ if they touch diagonally:
150
+
151
+ >>> s = generate_binary_structure(2,2)
152
+
153
+ or,
154
+
155
+ >>> s = [[1,1,1],
156
+ ... [1,1,1],
157
+ ... [1,1,1]]
158
+
159
+ Label the image using the new structuring element:
160
+
161
+ >>> labeled_array, num_features = label(a, structure=s)
162
+
163
+ Show the 2 labeled features (note that features 1, 3, and 4 from above are
164
+ now considered a single feature):
165
+
166
+ >>> num_features
167
+ 2
168
+ >>> labeled_array
169
+ array([[0, 0, 1, 1, 0, 0],
170
+ [0, 0, 0, 1, 0, 0],
171
+ [2, 2, 0, 0, 1, 0],
172
+ [0, 0, 0, 1, 0, 0]], dtype=int32)
173
+
174
+ """
175
+ input = np.asarray(input)
176
+ if np.iscomplexobj(input):
177
+ raise TypeError('Complex type not supported')
178
+ if structure is None:
179
+ structure = _morphology.generate_binary_structure(input.ndim, 1)
180
+ structure = np.asarray(structure, dtype=bool)
181
+ if structure.ndim != input.ndim:
182
+ raise RuntimeError('structure and input must have equal rank')
183
+ for ii in structure.shape:
184
+ if ii != 3:
185
+ raise ValueError('structure dimensions must be equal to 3')
186
+
187
+ # Use 32 bits if it's large enough for this image.
188
+ # _ni_label.label() needs two entries for background and
189
+ # foreground tracking
190
+ need_64bits = input.size >= (2**31 - 2)
191
+
192
+ if isinstance(output, np.ndarray):
193
+ if output.shape != input.shape:
194
+ raise ValueError("output shape not correct")
195
+ caller_provided_output = True
196
+ else:
197
+ caller_provided_output = False
198
+ if output is None:
199
+ output = np.empty(input.shape, np.intp if need_64bits else np.int32)
200
+ else:
201
+ output = np.empty(input.shape, output)
202
+
203
+ # handle scalars, 0-D arrays
204
+ if input.ndim == 0 or input.size == 0:
205
+ if input.ndim == 0:
206
+ # scalar
207
+ maxlabel = 1 if (input != 0) else 0
208
+ output[...] = maxlabel
209
+ else:
210
+ # 0-D
211
+ maxlabel = 0
212
+ if caller_provided_output:
213
+ return maxlabel
214
+ else:
215
+ return output, maxlabel
216
+
217
+ try:
218
+ max_label = _ni_label._label(input, structure, output)
219
+ except _ni_label.NeedMoreBits as e:
220
+ # Make another attempt with enough bits, then try to cast to the
221
+ # new type.
222
+ tmp_output = np.empty(input.shape, np.intp if need_64bits else np.int32)
223
+ max_label = _ni_label._label(input, structure, tmp_output)
224
+ output[...] = tmp_output[...]
225
+ if not np.all(output == tmp_output):
226
+ # refuse to return bad results
227
+ raise RuntimeError(
228
+ "insufficient bit-depth in requested output type"
229
+ ) from e
230
+
231
+ if caller_provided_output:
232
+ # result was written in-place
233
+ return max_label
234
+ else:
235
+ return output, max_label
236
+
237
+
238
+ def find_objects(input, max_label=0):
239
+ """
240
+ Find objects in a labeled array.
241
+
242
+ Parameters
243
+ ----------
244
+ input : ndarray of ints
245
+ Array containing objects defined by different labels. Labels with
246
+ value 0 are ignored.
247
+ max_label : int, optional
248
+ Maximum label to be searched for in `input`. If max_label is not
249
+ given, the positions of all objects are returned.
250
+
251
+ Returns
252
+ -------
253
+ object_slices : list of tuples
254
+ A list of tuples, with each tuple containing N slices (with N the
255
+ dimension of the input array). Slices correspond to the minimal
256
+ parallelepiped that contains the object. If a number is missing,
257
+ None is returned instead of a slice. The label ``l`` corresponds to
258
+ the index ``l-1`` in the returned list.
259
+
260
+ See Also
261
+ --------
262
+ label, center_of_mass
263
+
264
+ Notes
265
+ -----
266
+ This function is very useful for isolating a volume of interest inside
267
+ a 3-D array, that cannot be "seen through".
268
+
269
+ Examples
270
+ --------
271
+ >>> from scipy import ndimage
272
+ >>> import numpy as np
273
+ >>> a = np.zeros((6,6), dtype=int)
274
+ >>> a[2:4, 2:4] = 1
275
+ >>> a[4, 4] = 1
276
+ >>> a[:2, :3] = 2
277
+ >>> a[0, 5] = 3
278
+ >>> a
279
+ array([[2, 2, 2, 0, 0, 3],
280
+ [2, 2, 2, 0, 0, 0],
281
+ [0, 0, 1, 1, 0, 0],
282
+ [0, 0, 1, 1, 0, 0],
283
+ [0, 0, 0, 0, 1, 0],
284
+ [0, 0, 0, 0, 0, 0]])
285
+ >>> ndimage.find_objects(a)
286
+ [(slice(2, 5, None), slice(2, 5, None)),
287
+ (slice(0, 2, None), slice(0, 3, None)),
288
+ (slice(0, 1, None), slice(5, 6, None))]
289
+ >>> ndimage.find_objects(a, max_label=2)
290
+ [(slice(2, 5, None), slice(2, 5, None)), (slice(0, 2, None), slice(0, 3, None))]
291
+ >>> ndimage.find_objects(a == 1, max_label=2)
292
+ [(slice(2, 5, None), slice(2, 5, None)), None]
293
+
294
+ >>> loc = ndimage.find_objects(a)[0]
295
+ >>> a[loc]
296
+ array([[1, 1, 0],
297
+ [1, 1, 0],
298
+ [0, 0, 1]])
299
+
300
+ """
301
+ input = np.asarray(input)
302
+ if np.iscomplexobj(input):
303
+ raise TypeError('Complex type not supported')
304
+
305
+ if max_label < 1:
306
+ max_label = input.max()
307
+
308
+ return _nd_image.find_objects(input, max_label)
309
+
310
+
311
+ def value_indices(arr, *, ignore_value=None):
312
+ """
313
+ Find indices of each distinct value in given array.
314
+
315
+ Parameters
316
+ ----------
317
+ arr : ndarray of ints
318
+ Array containing integer values.
319
+ ignore_value : int, optional
320
+ This value will be ignored in searching the `arr` array. If not
321
+ given, all values found will be included in output. Default
322
+ is None.
323
+
324
+ Returns
325
+ -------
326
+ indices : dictionary
327
+ A Python dictionary of array indices for each distinct value. The
328
+ dictionary is keyed by the distinct values, the entries are array
329
+ index tuples covering all occurrences of the value within the
330
+ array.
331
+
332
+ This dictionary can occupy significant memory, usually several times
333
+ the size of the input array.
334
+
335
+ See Also
336
+ --------
337
+ label, maximum, median, minimum_position, extrema, sum, mean, variance,
338
+ standard_deviation, numpy.where, numpy.unique
339
+
340
+ Notes
341
+ -----
342
+ For a small array with few distinct values, one might use
343
+ `numpy.unique()` to find all possible values, and ``(arr == val)`` to
344
+ locate each value within that array. However, for large arrays,
345
+ with many distinct values, this can become extremely inefficient,
346
+ as locating each value would require a new search through the entire
347
+ array. Using this function, there is essentially one search, with
348
+ the indices saved for all distinct values.
349
+
350
+ This is useful when matching a categorical image (e.g. a segmentation
351
+ or classification) to an associated image of other data, allowing
352
+ any per-class statistic(s) to then be calculated. Provides a
353
+ more flexible alternative to functions like ``scipy.ndimage.mean()``
354
+ and ``scipy.ndimage.variance()``.
355
+
356
+ Some other closely related functionality, with different strengths and
357
+ weaknesses, can also be found in ``scipy.stats.binned_statistic()`` and
358
+ the `scikit-image <https://scikit-image.org/>`_ function
359
+ ``skimage.measure.regionprops()``.
360
+
361
+ Note for IDL users: this provides functionality equivalent to IDL's
362
+ REVERSE_INDICES option (as per the IDL documentation for the
363
+ `HISTOGRAM <https://www.l3harrisgeospatial.com/docs/histogram.html>`_
364
+ function).
365
+
366
+ .. versionadded:: 1.10.0
367
+
368
+ Examples
369
+ --------
370
+ >>> import numpy as np
371
+ >>> from scipy import ndimage
372
+ >>> a = np.zeros((6, 6), dtype=int)
373
+ >>> a[2:4, 2:4] = 1
374
+ >>> a[4, 4] = 1
375
+ >>> a[:2, :3] = 2
376
+ >>> a[0, 5] = 3
377
+ >>> a
378
+ array([[2, 2, 2, 0, 0, 3],
379
+ [2, 2, 2, 0, 0, 0],
380
+ [0, 0, 1, 1, 0, 0],
381
+ [0, 0, 1, 1, 0, 0],
382
+ [0, 0, 0, 0, 1, 0],
383
+ [0, 0, 0, 0, 0, 0]])
384
+ >>> val_indices = ndimage.value_indices(a)
385
+
386
+ The dictionary `val_indices` will have an entry for each distinct
387
+ value in the input array.
388
+
389
+ >>> val_indices.keys()
390
+ dict_keys([np.int64(0), np.int64(1), np.int64(2), np.int64(3)])
391
+
392
+ The entry for each value is an index tuple, locating the elements
393
+ with that value.
394
+
395
+ >>> ndx1 = val_indices[1]
396
+ >>> ndx1
397
+ (array([2, 2, 3, 3, 4]), array([2, 3, 2, 3, 4]))
398
+
399
+ This can be used to index into the original array, or any other
400
+ array with the same shape.
401
+
402
+ >>> a[ndx1]
403
+ array([1, 1, 1, 1, 1])
404
+
405
+ If the zeros were to be ignored, then the resulting dictionary
406
+ would no longer have an entry for zero.
407
+
408
+ >>> val_indices = ndimage.value_indices(a, ignore_value=0)
409
+ >>> val_indices.keys()
410
+ dict_keys([np.int64(1), np.int64(2), np.int64(3)])
411
+
412
+ """
413
+ # Cope with ignore_value being None, without too much extra complexity
414
+ # in the C code. If not None, the value is passed in as a numpy array
415
+ # with the same dtype as arr.
416
+ arr = np.asarray(arr)
417
+ ignore_value_arr = np.zeros((1,), dtype=arr.dtype)
418
+ ignoreIsNone = (ignore_value is None)
419
+ if not ignoreIsNone:
420
+ ignore_value_arr[0] = ignore_value_arr.dtype.type(ignore_value)
421
+
422
+ val_indices = _nd_image.value_indices(arr, ignoreIsNone, ignore_value_arr)
423
+ return val_indices
424
+
425
+
426
+ def labeled_comprehension(input, labels, index, func, out_dtype, default,
427
+ pass_positions=False):
428
+ """
429
+ Roughly equivalent to [func(input[labels == i]) for i in index].
430
+
431
+ Sequentially applies an arbitrary function (that works on array_like input)
432
+ to subsets of an N-D image array specified by `labels` and `index`.
433
+ The option exists to provide the function with positional parameters as the
434
+ second argument.
435
+
436
+ Parameters
437
+ ----------
438
+ input : array_like
439
+ Data from which to select `labels` to process.
440
+ labels : array_like or None
441
+ Labels to objects in `input`.
442
+ If not None, array must be same shape as `input`.
443
+ If None, `func` is applied to raveled `input`.
444
+ index : int, sequence of ints or None
445
+ Subset of `labels` to which to apply `func`.
446
+ If a scalar, a single value is returned.
447
+ If None, `func` is applied to all non-zero values of `labels`.
448
+ func : callable
449
+ Python function to apply to `labels` from `input`.
450
+ out_dtype : dtype
451
+ Dtype to use for `result`.
452
+ default : int, float or None
453
+ Default return value when an element of `index` does not exist
454
+ in `labels`.
455
+ pass_positions : bool, optional
456
+ If True, pass linear indices to `func` as a second argument.
457
+ Default is False.
458
+
459
+ Returns
460
+ -------
461
+ result : ndarray
462
+ Result of applying `func` to each of `labels` to `input` in `index`.
463
+
464
+ Examples
465
+ --------
466
+ >>> import numpy as np
467
+ >>> a = np.array([[1, 2, 0, 0],
468
+ ... [5, 3, 0, 4],
469
+ ... [0, 0, 0, 7],
470
+ ... [9, 3, 0, 0]])
471
+ >>> from scipy import ndimage
472
+ >>> lbl, nlbl = ndimage.label(a)
473
+ >>> lbls = np.arange(1, nlbl+1)
474
+ >>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, 0)
475
+ array([ 2.75, 5.5 , 6. ])
476
+
477
+ Falling back to `default`:
478
+
479
+ >>> lbls = np.arange(1, nlbl+2)
480
+ >>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, -1)
481
+ array([ 2.75, 5.5 , 6. , -1. ])
482
+
483
+ Passing positions:
484
+
485
+ >>> def fn(val, pos):
486
+ ... print("fn says: %s : %s" % (val, pos))
487
+ ... return (val.sum()) if (pos.sum() % 2 == 0) else (-val.sum())
488
+ ...
489
+ >>> ndimage.labeled_comprehension(a, lbl, lbls, fn, float, 0, True)
490
+ fn says: [1 2 5 3] : [0 1 4 5]
491
+ fn says: [4 7] : [ 7 11]
492
+ fn says: [9 3] : [12 13]
493
+ array([ 11., 11., -12., 0.])
494
+
495
+ """
496
+
497
+ as_scalar = np.isscalar(index)
498
+ input = np.asarray(input)
499
+
500
+ if pass_positions:
501
+ positions = np.arange(input.size).reshape(input.shape)
502
+
503
+ if labels is None:
504
+ if index is not None:
505
+ raise ValueError("index without defined labels")
506
+ if not pass_positions:
507
+ return func(input.ravel())
508
+ else:
509
+ return func(input.ravel(), positions.ravel())
510
+
511
+ labels = np.asarray(labels)
512
+
513
+ try:
514
+ input, labels = np.broadcast_arrays(input, labels)
515
+ except ValueError as e:
516
+ raise ValueError("input and labels must have the same shape "
517
+ "(excepting dimensions with width 1)") from e
518
+
519
+ if index is None:
520
+ if not pass_positions:
521
+ return func(input[labels > 0])
522
+ else:
523
+ return func(input[labels > 0], positions[labels > 0])
524
+
525
+ index = np.atleast_1d(index)
526
+ if np.any(index.astype(labels.dtype).astype(index.dtype) != index):
527
+ raise ValueError(f"Cannot convert index values from <{index.dtype}> to "
528
+ f"<{labels.dtype}> (labels' type) without loss of precision")
529
+
530
+ index = index.astype(labels.dtype)
531
+
532
+ # optimization: find min/max in index,
533
+ # and select those parts of labels, input, and positions
534
+ lo = index.min()
535
+ hi = index.max()
536
+ mask = (labels >= lo) & (labels <= hi)
537
+
538
+ # this also ravels the arrays
539
+ labels = labels[mask]
540
+ input = input[mask]
541
+ if pass_positions:
542
+ positions = positions[mask]
543
+
544
+ # sort everything by labels
545
+ label_order = labels.argsort()
546
+ labels = labels[label_order]
547
+ input = input[label_order]
548
+ if pass_positions:
549
+ positions = positions[label_order]
550
+
551
+ index_order = index.argsort()
552
+ sorted_index = index[index_order]
553
+
554
+ def do_map(inputs, output):
555
+ """labels must be sorted"""
556
+ nidx = sorted_index.size
557
+
558
+ # Find boundaries for each stretch of constant labels
559
+ # This could be faster, but we already paid N log N to sort labels.
560
+ lo = np.searchsorted(labels, sorted_index, side='left')
561
+ hi = np.searchsorted(labels, sorted_index, side='right')
562
+
563
+ for i, l, h in zip(range(nidx), lo, hi):
564
+ if l == h:
565
+ continue
566
+ output[i] = func(*[inp[l:h] for inp in inputs])
567
+
568
+ temp = np.empty(index.shape, out_dtype)
569
+ temp[:] = default
570
+ if not pass_positions:
571
+ do_map([input], temp)
572
+ else:
573
+ do_map([input, positions], temp)
574
+
575
+ output = np.zeros(index.shape, out_dtype)
576
+ output[index_order] = temp
577
+ if as_scalar:
578
+ output = output[0]
579
+
580
+ return output
581
+
582
+
583
+ def _safely_castable_to_int(dt):
584
+ """Test whether the NumPy data type `dt` can be safely cast to an int."""
585
+ int_size = np.dtype(int).itemsize
586
+ safe = ((np.issubdtype(dt, np.signedinteger) and dt.itemsize <= int_size) or
587
+ (np.issubdtype(dt, np.unsignedinteger) and dt.itemsize < int_size))
588
+ return safe
589
+
590
+
591
+ def _stats(input, labels=None, index=None, centered=False):
592
+ """Count, sum, and optionally compute (sum - centre)^2 of input by label
593
+
594
+ Parameters
595
+ ----------
596
+ input : array_like, N-D
597
+ The input data to be analyzed.
598
+ labels : array_like (N-D), optional
599
+ The labels of the data in `input`. This array must be broadcast
600
+ compatible with `input`; typically, it is the same shape as `input`.
601
+ If `labels` is None, all nonzero values in `input` are treated as
602
+ the single labeled group.
603
+ index : label or sequence of labels, optional
604
+ These are the labels of the groups for which the stats are computed.
605
+ If `index` is None, the stats are computed for the single group where
606
+ `labels` is greater than 0.
607
+ centered : bool, optional
608
+ If True, the centered sum of squares for each labeled group is
609
+ also returned. Default is False.
610
+
611
+ Returns
612
+ -------
613
+ counts : int or ndarray of ints
614
+ The number of elements in each labeled group.
615
+ sums : scalar or ndarray of scalars
616
+ The sums of the values in each labeled group.
617
+ sums_c : scalar or ndarray of scalars, optional
618
+ The sums of mean-centered squares of the values in each labeled group.
619
+ This is only returned if `centered` is True.
620
+
621
+ """
622
+ def single_group(vals):
623
+ if centered:
624
+ vals_c = vals - vals.mean()
625
+ return vals.size, vals.sum(), (vals_c * vals_c.conjugate()).sum()
626
+ else:
627
+ return vals.size, vals.sum()
628
+
629
+ input = np.asarray(input)
630
+ if labels is None:
631
+ return single_group(input)
632
+
633
+ labels = np.asarray(labels)
634
+ # ensure input and labels match sizes
635
+ input, labels = np.broadcast_arrays(input, labels)
636
+
637
+ if index is None:
638
+ return single_group(input[labels > 0])
639
+
640
+ if np.isscalar(index):
641
+ return single_group(input[labels == index])
642
+
643
+ def _sum_centered(labels):
644
+ # `labels` is expected to be an ndarray with the same shape as `input`.
645
+ # It must contain the label indices (which are not necessarily the labels
646
+ # themselves).
647
+ means = sums / counts
648
+ centered_input = input - means[labels]
649
+ # bincount expects 1-D inputs, so we ravel the arguments.
650
+ bc = np.bincount(labels.ravel(),
651
+ weights=(centered_input *
652
+ centered_input.conjugate()).ravel())
653
+ return bc
654
+
655
+ # Remap labels to unique integers if necessary, or if the largest
656
+ # label is larger than the number of values.
657
+
658
+ if (not _safely_castable_to_int(labels.dtype) or
659
+ labels.min() < 0 or labels.max() > labels.size):
660
+ # Use np.unique to generate the label indices. `new_labels` will
661
+ # be 1-D, but it should be interpreted as the flattened N-D array of
662
+ # label indices.
663
+ unique_labels, new_labels = np.unique(labels, return_inverse=True)
664
+ new_labels = np.reshape(new_labels, (-1,)) # flatten, since it may be >1-D
665
+ counts = np.bincount(new_labels)
666
+ sums = np.bincount(new_labels, weights=input.ravel())
667
+ if centered:
668
+ # Compute the sum of the mean-centered squares.
669
+ # We must reshape new_labels to the N-D shape of `input` before
670
+ # passing it _sum_centered.
671
+ sums_c = _sum_centered(new_labels.reshape(labels.shape))
672
+ idxs = np.searchsorted(unique_labels, index)
673
+ # make all of idxs valid
674
+ idxs[idxs >= unique_labels.size] = 0
675
+ found = (unique_labels[idxs] == index)
676
+ else:
677
+ # labels are an integer type allowed by bincount, and there aren't too
678
+ # many, so call bincount directly.
679
+ counts = np.bincount(labels.ravel())
680
+ sums = np.bincount(labels.ravel(), weights=input.ravel())
681
+ if centered:
682
+ sums_c = _sum_centered(labels)
683
+ # make sure all index values are valid
684
+ idxs = np.asanyarray(index, np.int_).copy()
685
+ found = (idxs >= 0) & (idxs < counts.size)
686
+ idxs[~found] = 0
687
+
688
+ counts = counts[idxs]
689
+ counts[~found] = 0
690
+ sums = sums[idxs]
691
+ sums[~found] = 0
692
+
693
+ if not centered:
694
+ return (counts, sums)
695
+ else:
696
+ sums_c = sums_c[idxs]
697
+ sums_c[~found] = 0
698
+ return (counts, sums, sums_c)
699
+
700
+
701
+ def sum(input, labels=None, index=None):
702
+ """
703
+ Calculate the sum of the values of the array.
704
+
705
+ Notes
706
+ -----
707
+ This is an alias for `ndimage.sum_labels` kept for backwards compatibility
708
+ reasons, for new code please prefer `sum_labels`. See the `sum_labels`
709
+ docstring for more details.
710
+
711
+ """
712
+ return sum_labels(input, labels, index)
713
+
714
+
715
+ def sum_labels(input, labels=None, index=None):
716
+ """
717
+ Calculate the sum of the values of the array.
718
+
719
+ Parameters
720
+ ----------
721
+ input : array_like
722
+ Values of `input` inside the regions defined by `labels`
723
+ are summed together.
724
+ labels : array_like of ints, optional
725
+ Assign labels to the values of the array. Has to have the same shape as
726
+ `input`.
727
+ index : array_like, optional
728
+ A single label number or a sequence of label numbers of
729
+ the objects to be measured.
730
+
731
+ Returns
732
+ -------
733
+ sum : ndarray or scalar
734
+ An array of the sums of values of `input` inside the regions defined
735
+ by `labels` with the same shape as `index`. If 'index' is None or scalar,
736
+ a scalar is returned.
737
+
738
+ See Also
739
+ --------
740
+ mean, median
741
+
742
+ Examples
743
+ --------
744
+ >>> from scipy import ndimage
745
+ >>> input = [0,1,2,3]
746
+ >>> labels = [1,1,2,2]
747
+ >>> ndimage.sum_labels(input, labels, index=[1,2])
748
+ [1.0, 5.0]
749
+ >>> ndimage.sum_labels(input, labels, index=1)
750
+ 1
751
+ >>> ndimage.sum_labels(input, labels)
752
+ 6
753
+
754
+
755
+ """
756
+ count, sum = _stats(input, labels, index)
757
+ return sum
758
+
759
+
760
+ def mean(input, labels=None, index=None):
761
+ """
762
+ Calculate the mean of the values of an array at labels.
763
+
764
+ Parameters
765
+ ----------
766
+ input : array_like
767
+ Array on which to compute the mean of elements over distinct
768
+ regions.
769
+ labels : array_like, optional
770
+ Array of labels of same shape, or broadcastable to the same shape as
771
+ `input`. All elements sharing the same label form one region over
772
+ which the mean of the elements is computed.
773
+ index : int or sequence of ints, optional
774
+ Labels of the objects over which the mean is to be computed.
775
+ Default is None, in which case the mean for all values where label is
776
+ greater than 0 is calculated.
777
+
778
+ Returns
779
+ -------
780
+ out : list
781
+ Sequence of same length as `index`, with the mean of the different
782
+ regions labeled by the labels in `index`.
783
+
784
+ See Also
785
+ --------
786
+ variance, standard_deviation, minimum, maximum, sum, label
787
+
788
+ Examples
789
+ --------
790
+ >>> from scipy import ndimage
791
+ >>> import numpy as np
792
+ >>> a = np.arange(25).reshape((5,5))
793
+ >>> labels = np.zeros_like(a)
794
+ >>> labels[3:5,3:5] = 1
795
+ >>> index = np.unique(labels)
796
+ >>> labels
797
+ array([[0, 0, 0, 0, 0],
798
+ [0, 0, 0, 0, 0],
799
+ [0, 0, 0, 0, 0],
800
+ [0, 0, 0, 1, 1],
801
+ [0, 0, 0, 1, 1]])
802
+ >>> index
803
+ array([0, 1])
804
+ >>> ndimage.mean(a, labels=labels, index=index)
805
+ [10.285714285714286, 21.0]
806
+
807
+ """
808
+
809
+ count, sum = _stats(input, labels, index)
810
+ return sum / np.asanyarray(count).astype(np.float64)
811
+
812
+
813
+ def variance(input, labels=None, index=None):
814
+ """
815
+ Calculate the variance of the values of an N-D image array, optionally at
816
+ specified sub-regions.
817
+
818
+ Parameters
819
+ ----------
820
+ input : array_like
821
+ Nd-image data to process.
822
+ labels : array_like, optional
823
+ Labels defining sub-regions in `input`.
824
+ If not None, must be same shape as `input`.
825
+ index : int or sequence of ints, optional
826
+ `labels` to include in output. If None (default), all values where
827
+ `labels` is non-zero are used.
828
+
829
+ Returns
830
+ -------
831
+ variance : float or ndarray
832
+ Values of variance, for each sub-region if `labels` and `index` are
833
+ specified.
834
+
835
+ See Also
836
+ --------
837
+ label, standard_deviation, maximum, minimum, extrema
838
+
839
+ Examples
840
+ --------
841
+ >>> import numpy as np
842
+ >>> a = np.array([[1, 2, 0, 0],
843
+ ... [5, 3, 0, 4],
844
+ ... [0, 0, 0, 7],
845
+ ... [9, 3, 0, 0]])
846
+ >>> from scipy import ndimage
847
+ >>> ndimage.variance(a)
848
+ 7.609375
849
+
850
+ Features to process can be specified using `labels` and `index`:
851
+
852
+ >>> lbl, nlbl = ndimage.label(a)
853
+ >>> ndimage.variance(a, lbl, index=np.arange(1, nlbl+1))
854
+ array([ 2.1875, 2.25 , 9. ])
855
+
856
+ If no index is given, all non-zero `labels` are processed:
857
+
858
+ >>> ndimage.variance(a, lbl)
859
+ 6.1875
860
+
861
+ """
862
+ count, sum, sum_c_sq = _stats(input, labels, index, centered=True)
863
+ return sum_c_sq / np.asanyarray(count).astype(float)
864
+
865
+
866
+ def standard_deviation(input, labels=None, index=None):
867
+ """
868
+ Calculate the standard deviation of the values of an N-D image array,
869
+ optionally at specified sub-regions.
870
+
871
+ Parameters
872
+ ----------
873
+ input : array_like
874
+ N-D image data to process.
875
+ labels : array_like, optional
876
+ Labels to identify sub-regions in `input`.
877
+ If not None, must be same shape as `input`.
878
+ index : int or sequence of ints, optional
879
+ `labels` to include in output. If None (default), all values where
880
+ `labels` is non-zero are used.
881
+
882
+ Returns
883
+ -------
884
+ standard_deviation : float or ndarray
885
+ Values of standard deviation, for each sub-region if `labels` and
886
+ `index` are specified.
887
+
888
+ See Also
889
+ --------
890
+ label, variance, maximum, minimum, extrema
891
+
892
+ Examples
893
+ --------
894
+ >>> import numpy as np
895
+ >>> a = np.array([[1, 2, 0, 0],
896
+ ... [5, 3, 0, 4],
897
+ ... [0, 0, 0, 7],
898
+ ... [9, 3, 0, 0]])
899
+ >>> from scipy import ndimage
900
+ >>> ndimage.standard_deviation(a)
901
+ 2.7585095613392387
902
+
903
+ Features to process can be specified using `labels` and `index`:
904
+
905
+ >>> lbl, nlbl = ndimage.label(a)
906
+ >>> ndimage.standard_deviation(a, lbl, index=np.arange(1, nlbl+1))
907
+ array([ 1.479, 1.5 , 3. ])
908
+
909
+ If no index is given, non-zero `labels` are processed:
910
+
911
+ >>> ndimage.standard_deviation(a, lbl)
912
+ 2.4874685927665499
913
+
914
+ """
915
+ return np.sqrt(variance(input, labels, index))
916
+
917
+
918
+ def _select(input, labels=None, index=None, find_min=False, find_max=False,
919
+ find_min_positions=False, find_max_positions=False,
920
+ find_median=False):
921
+ """Returns min, max, or both, plus their positions (if requested), and
922
+ median."""
923
+
924
+ input = np.asanyarray(input)
925
+
926
+ find_positions = find_min_positions or find_max_positions
927
+ positions = None
928
+ if find_positions:
929
+ positions = np.arange(input.size).reshape(input.shape)
930
+
931
+ def single_group(vals, positions):
932
+ result = []
933
+ if find_min:
934
+ result += [vals.min()]
935
+ if find_min_positions:
936
+ result += [positions[vals == vals.min()][0]]
937
+ if find_max:
938
+ result += [vals.max()]
939
+ if find_max_positions:
940
+ result += [positions[vals == vals.max()][0]]
941
+ if find_median:
942
+ result += [np.median(vals)]
943
+ return result
944
+
945
+ if labels is None:
946
+ return single_group(input, positions)
947
+
948
+ labels = np.asarray(labels)
949
+ # ensure input and labels match sizes
950
+ input, labels = np.broadcast_arrays(input, labels)
951
+
952
+ if index is None:
953
+ mask = (labels > 0)
954
+ masked_positions = None
955
+ if find_positions:
956
+ masked_positions = positions[mask]
957
+ return single_group(input[mask], masked_positions)
958
+
959
+ if np.isscalar(index):
960
+ mask = (labels == index)
961
+ masked_positions = None
962
+ if find_positions:
963
+ masked_positions = positions[mask]
964
+ return single_group(input[mask], masked_positions)
965
+
966
+ index = np.asarray(index)
967
+
968
+ # remap labels to unique integers if necessary, or if the largest
969
+ # label is larger than the number of values.
970
+ if (not _safely_castable_to_int(labels.dtype) or
971
+ labels.min() < 0 or labels.max() > labels.size):
972
+ # remap labels, and indexes
973
+ unique_labels, labels = np.unique(labels, return_inverse=True)
974
+ idxs = np.searchsorted(unique_labels, index)
975
+
976
+ # make all of idxs valid
977
+ idxs[idxs >= unique_labels.size] = 0
978
+ found = (unique_labels[idxs] == index)
979
+ else:
980
+ # labels are an integer type, and there aren't too many
981
+ idxs = np.asanyarray(index, np.int_).copy()
982
+ found = (idxs >= 0) & (idxs <= labels.max())
983
+
984
+ idxs[~ found] = labels.max() + 1
985
+
986
+ if find_median:
987
+ order = np.lexsort((input.ravel(), labels.ravel()))
988
+ else:
989
+ order = input.ravel().argsort()
990
+ input = input.ravel()[order]
991
+ labels = labels.ravel()[order]
992
+ if find_positions:
993
+ positions = positions.ravel()[order]
994
+
995
+ result = []
996
+ if find_min:
997
+ mins = np.zeros(labels.max() + 2, input.dtype)
998
+ mins[labels[::-1]] = input[::-1]
999
+ result += [mins[idxs]]
1000
+ if find_min_positions:
1001
+ minpos = np.zeros(labels.max() + 2, int)
1002
+ minpos[labels[::-1]] = positions[::-1]
1003
+ result += [minpos[idxs]]
1004
+ if find_max:
1005
+ maxs = np.zeros(labels.max() + 2, input.dtype)
1006
+ maxs[labels] = input
1007
+ result += [maxs[idxs]]
1008
+ if find_max_positions:
1009
+ maxpos = np.zeros(labels.max() + 2, int)
1010
+ maxpos[labels] = positions
1011
+ result += [maxpos[idxs]]
1012
+ if find_median:
1013
+ locs = np.arange(len(labels))
1014
+ lo = np.zeros(labels.max() + 2, np.int_)
1015
+ lo[labels[::-1]] = locs[::-1]
1016
+ hi = np.zeros(labels.max() + 2, np.int_)
1017
+ hi[labels] = locs
1018
+ lo = lo[idxs]
1019
+ hi = hi[idxs]
1020
+ # lo is an index to the lowest value in input for each label,
1021
+ # hi is an index to the largest value.
1022
+ # move them to be either the same ((hi - lo) % 2 == 0) or next
1023
+ # to each other ((hi - lo) % 2 == 1), then average.
1024
+ step = (hi - lo) // 2
1025
+ lo += step
1026
+ hi -= step
1027
+ if (np.issubdtype(input.dtype, np.integer)
1028
+ or np.issubdtype(input.dtype, np.bool_)):
1029
+ # avoid integer overflow or boolean addition (gh-12836)
1030
+ result += [(input[lo].astype('d') + input[hi].astype('d')) / 2.0]
1031
+ else:
1032
+ result += [(input[lo] + input[hi]) / 2.0]
1033
+
1034
+ return result
1035
+
1036
+
1037
+ def minimum(input, labels=None, index=None):
1038
+ """
1039
+ Calculate the minimum of the values of an array over labeled regions.
1040
+
1041
+ Parameters
1042
+ ----------
1043
+ input : array_like
1044
+ Array_like of values. For each region specified by `labels`, the
1045
+ minimal values of `input` over the region is computed.
1046
+ labels : array_like, optional
1047
+ An array_like of integers marking different regions over which the
1048
+ minimum value of `input` is to be computed. `labels` must have the
1049
+ same shape as `input`. If `labels` is not specified, the minimum
1050
+ over the whole array is returned.
1051
+ index : array_like, optional
1052
+ A list of region labels that are taken into account for computing the
1053
+ minima. If index is None, the minimum over all elements where `labels`
1054
+ is non-zero is returned.
1055
+
1056
+ Returns
1057
+ -------
1058
+ output : a scalar or list of integers or floats based on input type.
1059
+ List of minima of `input` over the regions determined by `labels` and
1060
+ whose index is in `index`. If `index` or `labels` are not specified, a
1061
+ float is returned: the minimal value of `input` if `labels` is None,
1062
+ and the minimal value of elements where `labels` is greater than zero
1063
+ if `index` is None.
1064
+
1065
+ See Also
1066
+ --------
1067
+ label, maximum, median, minimum_position, extrema, sum, mean, variance,
1068
+ standard_deviation
1069
+
1070
+ Notes
1071
+ -----
1072
+ The function returns a Python list and not a NumPy array, use
1073
+ `np.array` to convert the list to an array.
1074
+
1075
+ Examples
1076
+ --------
1077
+ >>> from scipy import ndimage
1078
+ >>> import numpy as np
1079
+ >>> a = np.array([[1, 2, 0, 0],
1080
+ ... [5, 3, 0, 4],
1081
+ ... [0, 0, 0, 7],
1082
+ ... [9, 3, 0, 0]])
1083
+ >>> labels, labels_nb = ndimage.label(a)
1084
+ >>> labels
1085
+ array([[1, 1, 0, 0],
1086
+ [1, 1, 0, 2],
1087
+ [0, 0, 0, 2],
1088
+ [3, 3, 0, 0]], dtype=int32)
1089
+ >>> ndimage.minimum(a, labels=labels, index=np.arange(1, labels_nb + 1))
1090
+ [1, 4, 3]
1091
+ >>> ndimage.minimum(a)
1092
+ 0
1093
+ >>> ndimage.minimum(a, labels=labels)
1094
+ 1
1095
+
1096
+ """
1097
+ return _select(input, labels, index, find_min=True)[0]
1098
+
1099
+
1100
+ def maximum(input, labels=None, index=None):
1101
+ """
1102
+ Calculate the maximum of the values of an array over labeled regions.
1103
+
1104
+ Parameters
1105
+ ----------
1106
+ input : array_like
1107
+ Array_like of values. For each region specified by `labels`, the
1108
+ maximal values of `input` over the region is computed.
1109
+ labels : array_like, optional
1110
+ An array of integers marking different regions over which the
1111
+ maximum value of `input` is to be computed. `labels` must have the
1112
+ same shape as `input`. If `labels` is not specified, the maximum
1113
+ over the whole array is returned.
1114
+ index : array_like, optional
1115
+ A list of region labels that are taken into account for computing the
1116
+ maxima. If index is None, the maximum over all elements where `labels`
1117
+ is non-zero is returned.
1118
+
1119
+ Returns
1120
+ -------
1121
+ output : a scalar or list of integers or floats based on input type.
1122
+ List of maxima of `input` over the regions determined by `labels` and
1123
+ whose index is in `index`. If `index` or `labels` are not specified, a
1124
+ float is returned: the maximal value of `input` if `labels` is None,
1125
+ and the maximal value of elements where `labels` is greater than zero
1126
+ if `index` is None.
1127
+
1128
+ See Also
1129
+ --------
1130
+ label, minimum, median, maximum_position, extrema, sum, mean, variance,
1131
+ standard_deviation
1132
+
1133
+ Notes
1134
+ -----
1135
+ The function returns a Python list and not a NumPy array, use
1136
+ `np.array` to convert the list to an array.
1137
+
1138
+ Examples
1139
+ --------
1140
+ >>> import numpy as np
1141
+ >>> a = np.arange(16).reshape((4,4))
1142
+ >>> a
1143
+ array([[ 0, 1, 2, 3],
1144
+ [ 4, 5, 6, 7],
1145
+ [ 8, 9, 10, 11],
1146
+ [12, 13, 14, 15]])
1147
+ >>> labels = np.zeros_like(a)
1148
+ >>> labels[:2,:2] = 1
1149
+ >>> labels[2:, 1:3] = 2
1150
+ >>> labels
1151
+ array([[1, 1, 0, 0],
1152
+ [1, 1, 0, 0],
1153
+ [0, 2, 2, 0],
1154
+ [0, 2, 2, 0]])
1155
+ >>> from scipy import ndimage
1156
+ >>> ndimage.maximum(a)
1157
+ 15
1158
+ >>> ndimage.maximum(a, labels=labels, index=[1,2])
1159
+ [5, 14]
1160
+ >>> ndimage.maximum(a, labels=labels)
1161
+ 14
1162
+
1163
+ >>> b = np.array([[1, 2, 0, 0],
1164
+ ... [5, 3, 0, 4],
1165
+ ... [0, 0, 0, 7],
1166
+ ... [9, 3, 0, 0]])
1167
+ >>> labels, labels_nb = ndimage.label(b)
1168
+ >>> labels
1169
+ array([[1, 1, 0, 0],
1170
+ [1, 1, 0, 2],
1171
+ [0, 0, 0, 2],
1172
+ [3, 3, 0, 0]], dtype=int32)
1173
+ >>> ndimage.maximum(b, labels=labels, index=np.arange(1, labels_nb + 1))
1174
+ [5, 7, 9]
1175
+
1176
+ """
1177
+ return _select(input, labels, index, find_max=True)[0]
1178
+
1179
+
1180
+ def median(input, labels=None, index=None):
1181
+ """
1182
+ Calculate the median of the values of an array over labeled regions.
1183
+
1184
+ Parameters
1185
+ ----------
1186
+ input : array_like
1187
+ Array_like of values. For each region specified by `labels`, the
1188
+ median value of `input` over the region is computed.
1189
+ labels : array_like, optional
1190
+ An array_like of integers marking different regions over which the
1191
+ median value of `input` is to be computed. `labels` must have the
1192
+ same shape as `input`. If `labels` is not specified, the median
1193
+ over the whole array is returned.
1194
+ index : array_like, optional
1195
+ A list of region labels that are taken into account for computing the
1196
+ medians. If index is None, the median over all elements where `labels`
1197
+ is non-zero is returned.
1198
+
1199
+ Returns
1200
+ -------
1201
+ median : float or list of floats
1202
+ List of medians of `input` over the regions determined by `labels` and
1203
+ whose index is in `index`. If `index` or `labels` are not specified, a
1204
+ float is returned: the median value of `input` if `labels` is None,
1205
+ and the median value of elements where `labels` is greater than zero
1206
+ if `index` is None.
1207
+
1208
+ See Also
1209
+ --------
1210
+ label, minimum, maximum, extrema, sum, mean, variance, standard_deviation
1211
+
1212
+ Notes
1213
+ -----
1214
+ The function returns a Python list and not a NumPy array, use
1215
+ `np.array` to convert the list to an array.
1216
+
1217
+ Examples
1218
+ --------
1219
+ >>> from scipy import ndimage
1220
+ >>> import numpy as np
1221
+ >>> a = np.array([[1, 2, 0, 1],
1222
+ ... [5, 3, 0, 4],
1223
+ ... [0, 0, 0, 7],
1224
+ ... [9, 3, 0, 0]])
1225
+ >>> labels, labels_nb = ndimage.label(a)
1226
+ >>> labels
1227
+ array([[1, 1, 0, 2],
1228
+ [1, 1, 0, 2],
1229
+ [0, 0, 0, 2],
1230
+ [3, 3, 0, 0]], dtype=int32)
1231
+ >>> ndimage.median(a, labels=labels, index=np.arange(1, labels_nb + 1))
1232
+ [2.5, 4.0, 6.0]
1233
+ >>> ndimage.median(a)
1234
+ 1.0
1235
+ >>> ndimage.median(a, labels=labels)
1236
+ 3.0
1237
+
1238
+ """
1239
+ return _select(input, labels, index, find_median=True)[0]
1240
+
1241
+
1242
+ def minimum_position(input, labels=None, index=None):
1243
+ """
1244
+ Find the positions of the minimums of the values of an array at labels.
1245
+
1246
+ Parameters
1247
+ ----------
1248
+ input : array_like
1249
+ Array_like of values.
1250
+ labels : array_like, optional
1251
+ An array of integers marking different regions over which the
1252
+ position of the minimum value of `input` is to be computed.
1253
+ `labels` must have the same shape as `input`. If `labels` is not
1254
+ specified, the location of the first minimum over the whole
1255
+ array is returned.
1256
+
1257
+ The `labels` argument only works when `index` is specified.
1258
+ index : array_like, optional
1259
+ A list of region labels that are taken into account for finding the
1260
+ location of the minima. If `index` is None, the ``first`` minimum
1261
+ over all elements where `labels` is non-zero is returned.
1262
+
1263
+ The `index` argument only works when `labels` is specified.
1264
+
1265
+ Returns
1266
+ -------
1267
+ output : list of tuples of ints
1268
+ Tuple of ints or list of tuples of ints that specify the location
1269
+ of minima of `input` over the regions determined by `labels` and
1270
+ whose index is in `index`.
1271
+
1272
+ If `index` or `labels` are not specified, a tuple of ints is
1273
+ returned specifying the location of the first minimal value of `input`.
1274
+
1275
+ See Also
1276
+ --------
1277
+ label, minimum, median, maximum_position, extrema, sum, mean, variance,
1278
+ standard_deviation
1279
+
1280
+ Examples
1281
+ --------
1282
+ >>> import numpy as np
1283
+ >>> a = np.array([[10, 20, 30],
1284
+ ... [40, 80, 100],
1285
+ ... [1, 100, 200]])
1286
+ >>> b = np.array([[1, 2, 0, 1],
1287
+ ... [5, 3, 0, 4],
1288
+ ... [0, 0, 0, 7],
1289
+ ... [9, 3, 0, 0]])
1290
+
1291
+ >>> from scipy import ndimage
1292
+
1293
+ >>> ndimage.minimum_position(a)
1294
+ (2, 0)
1295
+ >>> ndimage.minimum_position(b)
1296
+ (0, 2)
1297
+
1298
+ Features to process can be specified using `labels` and `index`:
1299
+
1300
+ >>> label, pos = ndimage.label(a)
1301
+ >>> ndimage.minimum_position(a, label, index=np.arange(1, pos+1))
1302
+ [(2, 0)]
1303
+
1304
+ >>> label, pos = ndimage.label(b)
1305
+ >>> ndimage.minimum_position(b, label, index=np.arange(1, pos+1))
1306
+ [(0, 0), (0, 3), (3, 1)]
1307
+
1308
+ """
1309
+ dims = np.array(np.asarray(input).shape)
1310
+ # see np.unravel_index to understand this line.
1311
+ dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1]
1312
+
1313
+ result = _select(input, labels, index, find_min_positions=True)[0]
1314
+
1315
+ if np.isscalar(result):
1316
+ return tuple((result // dim_prod) % dims)
1317
+
1318
+ return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
1319
+
1320
+
1321
+ def maximum_position(input, labels=None, index=None):
1322
+ """
1323
+ Find the positions of the maximums of the values of an array at labels.
1324
+
1325
+ For each region specified by `labels`, the position of the maximum
1326
+ value of `input` within the region is returned.
1327
+
1328
+ Parameters
1329
+ ----------
1330
+ input : array_like
1331
+ Array_like of values.
1332
+ labels : array_like, optional
1333
+ An array of integers marking different regions over which the
1334
+ position of the maximum value of `input` is to be computed.
1335
+ `labels` must have the same shape as `input`. If `labels` is not
1336
+ specified, the location of the first maximum over the whole
1337
+ array is returned.
1338
+
1339
+ The `labels` argument only works when `index` is specified.
1340
+ index : array_like, optional
1341
+ A list of region labels that are taken into account for finding the
1342
+ location of the maxima. If `index` is None, the first maximum
1343
+ over all elements where `labels` is non-zero is returned.
1344
+
1345
+ The `index` argument only works when `labels` is specified.
1346
+
1347
+ Returns
1348
+ -------
1349
+ output : list of tuples of ints
1350
+ List of tuples of ints that specify the location of maxima of
1351
+ `input` over the regions determined by `labels` and whose index
1352
+ is in `index`.
1353
+
1354
+ If `index` or `labels` are not specified, a tuple of ints is
1355
+ returned specifying the location of the ``first`` maximal value
1356
+ of `input`.
1357
+
1358
+ See Also
1359
+ --------
1360
+ label, minimum, median, maximum_position, extrema, sum, mean, variance,
1361
+ standard_deviation
1362
+
1363
+ Examples
1364
+ --------
1365
+ >>> from scipy import ndimage
1366
+ >>> import numpy as np
1367
+ >>> a = np.array([[1, 2, 0, 0],
1368
+ ... [5, 3, 0, 4],
1369
+ ... [0, 0, 0, 7],
1370
+ ... [9, 3, 0, 0]])
1371
+ >>> ndimage.maximum_position(a)
1372
+ (3, 0)
1373
+
1374
+ Features to process can be specified using `labels` and `index`:
1375
+
1376
+ >>> lbl = np.array([[0, 1, 2, 3],
1377
+ ... [0, 1, 2, 3],
1378
+ ... [0, 1, 2, 3],
1379
+ ... [0, 1, 2, 3]])
1380
+ >>> ndimage.maximum_position(a, lbl, 1)
1381
+ (1, 1)
1382
+
1383
+ If no index is given, non-zero `labels` are processed:
1384
+
1385
+ >>> ndimage.maximum_position(a, lbl)
1386
+ (2, 3)
1387
+
1388
+ If there are no maxima, the position of the first element is returned:
1389
+
1390
+ >>> ndimage.maximum_position(a, lbl, 2)
1391
+ (0, 2)
1392
+
1393
+ """
1394
+ dims = np.array(np.asarray(input).shape)
1395
+ # see np.unravel_index to understand this line.
1396
+ dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1]
1397
+
1398
+ result = _select(input, labels, index, find_max_positions=True)[0]
1399
+
1400
+ if np.isscalar(result):
1401
+ return tuple((result // dim_prod) % dims)
1402
+
1403
+ return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
1404
+
1405
+
1406
+ def extrema(input, labels=None, index=None):
1407
+ """
1408
+ Calculate the minimums and maximums of the values of an array
1409
+ at labels, along with their positions.
1410
+
1411
+ Parameters
1412
+ ----------
1413
+ input : ndarray
1414
+ N-D image data to process.
1415
+ labels : ndarray, optional
1416
+ Labels of features in input.
1417
+ If not None, must be same shape as `input`.
1418
+ index : int or sequence of ints, optional
1419
+ Labels to include in output. If None (default), all values where
1420
+ non-zero `labels` are used.
1421
+
1422
+ Returns
1423
+ -------
1424
+ minimums, maximums : int or ndarray
1425
+ Values of minimums and maximums in each feature.
1426
+ min_positions, max_positions : tuple or list of tuples
1427
+ Each tuple gives the N-D coordinates of the corresponding minimum
1428
+ or maximum.
1429
+
1430
+ See Also
1431
+ --------
1432
+ maximum, minimum, maximum_position, minimum_position, center_of_mass
1433
+
1434
+ Examples
1435
+ --------
1436
+ >>> import numpy as np
1437
+ >>> a = np.array([[1, 2, 0, 0],
1438
+ ... [5, 3, 0, 4],
1439
+ ... [0, 0, 0, 7],
1440
+ ... [9, 3, 0, 0]])
1441
+ >>> from scipy import ndimage
1442
+ >>> ndimage.extrema(a)
1443
+ (0, 9, (0, 2), (3, 0))
1444
+
1445
+ Features to process can be specified using `labels` and `index`:
1446
+
1447
+ >>> lbl, nlbl = ndimage.label(a)
1448
+ >>> ndimage.extrema(a, lbl, index=np.arange(1, nlbl+1))
1449
+ (array([1, 4, 3]),
1450
+ array([5, 7, 9]),
1451
+ [(0, 0), (1, 3), (3, 1)],
1452
+ [(1, 0), (2, 3), (3, 0)])
1453
+
1454
+ If no index is given, non-zero `labels` are processed:
1455
+
1456
+ >>> ndimage.extrema(a, lbl)
1457
+ (1, 9, (0, 0), (3, 0))
1458
+
1459
+ """
1460
+ dims = np.array(np.asarray(input).shape)
1461
+ # see np.unravel_index to understand this line.
1462
+ dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1]
1463
+
1464
+ minimums, min_positions, maximums, max_positions = _select(input, labels,
1465
+ index,
1466
+ find_min=True,
1467
+ find_max=True,
1468
+ find_min_positions=True,
1469
+ find_max_positions=True)
1470
+
1471
+ if np.isscalar(minimums):
1472
+ return (minimums, maximums, tuple((min_positions // dim_prod) % dims),
1473
+ tuple((max_positions // dim_prod) % dims))
1474
+
1475
+ min_positions = [
1476
+ tuple(v) for v in (min_positions.reshape(-1, 1) // dim_prod) % dims
1477
+ ]
1478
+ max_positions = [
1479
+ tuple(v) for v in (max_positions.reshape(-1, 1) // dim_prod) % dims
1480
+ ]
1481
+
1482
+ return minimums, maximums, min_positions, max_positions
1483
+
1484
+
1485
+ def center_of_mass(input, labels=None, index=None):
1486
+ """
1487
+ Calculate the center of mass of the values of an array at labels.
1488
+
1489
+ Parameters
1490
+ ----------
1491
+ input : ndarray
1492
+ Data from which to calculate center-of-mass. The masses can either
1493
+ be positive or negative.
1494
+ labels : ndarray, optional
1495
+ Labels for objects in `input`, as generated by `ndimage.label`.
1496
+ Only used with `index`. Dimensions must be the same as `input`.
1497
+ index : int or sequence of ints, optional
1498
+ Labels for which to calculate centers-of-mass. If not specified,
1499
+ the combined center of mass of all labels greater than zero
1500
+ will be calculated. Only used with `labels`.
1501
+
1502
+ Returns
1503
+ -------
1504
+ center_of_mass : tuple, or list of tuples
1505
+ Coordinates of centers-of-mass.
1506
+
1507
+ Examples
1508
+ --------
1509
+ >>> import numpy as np
1510
+ >>> a = np.array(([0,0,0,0],
1511
+ ... [0,1,1,0],
1512
+ ... [0,1,1,0],
1513
+ ... [0,1,1,0]))
1514
+ >>> from scipy import ndimage
1515
+ >>> ndimage.center_of_mass(a)
1516
+ (2.0, 1.5)
1517
+
1518
+ Calculation of multiple objects in an image
1519
+
1520
+ >>> b = np.array(([0,1,1,0],
1521
+ ... [0,1,0,0],
1522
+ ... [0,0,0,0],
1523
+ ... [0,0,1,1],
1524
+ ... [0,0,1,1]))
1525
+ >>> lbl = ndimage.label(b)[0]
1526
+ >>> ndimage.center_of_mass(b, lbl, [1,2])
1527
+ [(0.33333333333333331, 1.3333333333333333), (3.5, 2.5)]
1528
+
1529
+ Negative masses are also accepted, which can occur for example when
1530
+ bias is removed from measured data due to random noise.
1531
+
1532
+ >>> c = np.array(([-1,0,0,0],
1533
+ ... [0,-1,-1,0],
1534
+ ... [0,1,-1,0],
1535
+ ... [0,1,1,0]))
1536
+ >>> ndimage.center_of_mass(c)
1537
+ (-4.0, 1.0)
1538
+
1539
+ If there are division by zero issues, the function does not raise an
1540
+ error but rather issues a RuntimeWarning before returning inf and/or NaN.
1541
+
1542
+ >>> d = np.array([-1, 1])
1543
+ >>> ndimage.center_of_mass(d)
1544
+ (inf,)
1545
+ """
1546
+ input = np.asarray(input)
1547
+ normalizer = sum_labels(input, labels, index)
1548
+ grids = np.ogrid[[slice(0, i) for i in input.shape]]
1549
+
1550
+ results = [sum_labels(input * grids[dir].astype(float), labels, index) / normalizer
1551
+ for dir in range(input.ndim)]
1552
+
1553
+ if np.isscalar(results[0]):
1554
+ return tuple(results)
1555
+
1556
+ return [tuple(v) for v in np.array(results).T]
1557
+
1558
+
1559
+ def histogram(input, min, max, bins, labels=None, index=None):
1560
+ """
1561
+ Calculate the histogram of the values of an array, optionally at labels.
1562
+
1563
+ Histogram calculates the frequency of values in an array within bins
1564
+ determined by `min`, `max`, and `bins`. The `labels` and `index`
1565
+ keywords can limit the scope of the histogram to specified sub-regions
1566
+ within the array.
1567
+
1568
+ Parameters
1569
+ ----------
1570
+ input : array_like
1571
+ Data for which to calculate histogram.
1572
+ min, max : int
1573
+ Minimum and maximum values of range of histogram bins.
1574
+ bins : int
1575
+ Number of bins.
1576
+ labels : array_like, optional
1577
+ Labels for objects in `input`.
1578
+ If not None, must be same shape as `input`.
1579
+ index : int or sequence of ints, optional
1580
+ Label or labels for which to calculate histogram. If None, all values
1581
+ where label is greater than zero are used
1582
+
1583
+ Returns
1584
+ -------
1585
+ hist : ndarray
1586
+ Histogram counts.
1587
+
1588
+ Examples
1589
+ --------
1590
+ >>> import numpy as np
1591
+ >>> a = np.array([[ 0. , 0.2146, 0.5962, 0. ],
1592
+ ... [ 0. , 0.7778, 0. , 0. ],
1593
+ ... [ 0. , 0. , 0. , 0. ],
1594
+ ... [ 0. , 0. , 0.7181, 0.2787],
1595
+ ... [ 0. , 0. , 0.6573, 0.3094]])
1596
+ >>> from scipy import ndimage
1597
+ >>> ndimage.histogram(a, 0, 1, 10)
1598
+ array([13, 0, 2, 1, 0, 1, 1, 2, 0, 0])
1599
+
1600
+ With labels and no indices, non-zero elements are counted:
1601
+
1602
+ >>> lbl, nlbl = ndimage.label(a)
1603
+ >>> ndimage.histogram(a, 0, 1, 10, lbl)
1604
+ array([0, 0, 2, 1, 0, 1, 1, 2, 0, 0])
1605
+
1606
+ Indices can be used to count only certain objects:
1607
+
1608
+ >>> ndimage.histogram(a, 0, 1, 10, lbl, 2)
1609
+ array([0, 0, 1, 1, 0, 0, 1, 1, 0, 0])
1610
+
1611
+ """
1612
+ _bins = np.linspace(min, max, bins + 1)
1613
+
1614
+ def _hist(vals):
1615
+ return np.histogram(vals, _bins)[0]
1616
+
1617
+ return labeled_comprehension(input, labels, index, _hist, object, None,
1618
+ pass_positions=False)
1619
+
1620
+
1621
+ def watershed_ift(input, markers, structure=None, output=None):
1622
+ """
1623
+ Apply watershed from markers using image foresting transform algorithm.
1624
+
1625
+ Parameters
1626
+ ----------
1627
+ input : array_like
1628
+ Input.
1629
+ markers : array_like
1630
+ Markers are points within each watershed that form the beginning
1631
+ of the process. Negative markers are considered background markers
1632
+ which are processed after the other markers.
1633
+ structure : structure element, optional
1634
+ A structuring element defining the connectivity of the object can be
1635
+ provided. If None, an element is generated with a squared
1636
+ connectivity equal to one.
1637
+ output : ndarray, optional
1638
+ An output array can optionally be provided. The same shape as input.
1639
+
1640
+ Returns
1641
+ -------
1642
+ watershed_ift : ndarray
1643
+ Output. Same shape as `input`.
1644
+
1645
+ References
1646
+ ----------
1647
+ .. [1] A.X. Falcao, J. Stolfi and R. de Alencar Lotufo, "The image
1648
+ foresting transform: theory, algorithms, and applications",
1649
+ Pattern Analysis and Machine Intelligence, vol. 26, pp. 19-29, 2004.
1650
+
1651
+ """
1652
+ input = np.asarray(input)
1653
+ if input.dtype.type not in [np.uint8, np.uint16]:
1654
+ raise TypeError('only 8 and 16 unsigned inputs are supported')
1655
+
1656
+ if structure is None:
1657
+ structure = _morphology.generate_binary_structure(input.ndim, 1)
1658
+ structure = np.asarray(structure, dtype=bool)
1659
+ if structure.ndim != input.ndim:
1660
+ raise RuntimeError('structure and input must have equal rank')
1661
+ for ii in structure.shape:
1662
+ if ii != 3:
1663
+ raise RuntimeError('structure dimensions must be equal to 3')
1664
+
1665
+ if not structure.flags.contiguous:
1666
+ structure = structure.copy()
1667
+ markers = np.asarray(markers)
1668
+ if input.shape != markers.shape:
1669
+ raise RuntimeError('input and markers must have equal shape')
1670
+
1671
+ integral_types = [np.int8,
1672
+ np.int16,
1673
+ np.int32,
1674
+ np.int64,
1675
+ np.intc,
1676
+ np.intp]
1677
+
1678
+ if markers.dtype.type not in integral_types:
1679
+ raise RuntimeError('marker should be of integer type')
1680
+
1681
+ if isinstance(output, np.ndarray):
1682
+ if output.dtype.type not in integral_types:
1683
+ raise RuntimeError('output should be of integer type')
1684
+ else:
1685
+ output = markers.dtype
1686
+
1687
+ output = _ni_support._get_output(output, input)
1688
+ _nd_image.watershed_ift(input, markers, structure, output)
1689
+ return output
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_morphology.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-darwin.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:35fcb2473b289e07fec6786a16f743227829c5c7b7d223c2a46a924c2a0cb371
3
+ size 156160
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ndimage_api.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """This is the 'bare' ndimage API.
2
+
3
+ This --- private! --- module only collects implementations of public ndimage API
4
+ for _support_alternative_backends.
5
+ The latter --- also private! --- module adds delegation to CuPy etc and
6
+ re-exports decorated names to __init__.py
7
+ """
8
+
9
+ from ._filters import * # noqa: F403
10
+ from ._fourier import * # noqa: F403
11
+ from ._interpolation import * # noqa: F403
12
+ from ._measurements import * # noqa: F403
13
+ from ._morphology import * # noqa: F403
14
+
15
+ # '@' due to pytest bug, scipy/scipy#22236
16
+ __all__ = [s for s in dir() if not s.startswith(('_', '@'))]
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ni_docstrings.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Docstring components common to several ndimage functions."""
2
+ from typing import Final
3
+
4
+ from scipy._lib import doccer
5
+
6
+ __all__ = ['docfiller']
7
+
8
+
9
+ _input_doc = (
10
+ """input : array_like
11
+ The input array.""")
12
+ _axis_doc = (
13
+ """axis : int, optional
14
+ The axis of `input` along which to calculate. Default is -1.""")
15
+ _output_doc = (
16
+ """output : array or dtype, optional
17
+ The array in which to place the output, or the dtype of the
18
+ returned array. By default an array of the same dtype as input
19
+ will be created.""")
20
+ _nan_doc = (
21
+ """The behavior of this function with NaN elements is undefined. To control
22
+ behavior in the presence of NaNs, consider using `vectorized_filter`.""")
23
+ _size_foot_doc = (
24
+ """size : scalar or tuple, optional
25
+ See footprint, below. Ignored if footprint is given.
26
+ footprint : array, optional
27
+ Either `size` or `footprint` must be defined. `size` gives
28
+ the shape that is taken from the input array, at every element
29
+ position, to define the input to the filter function.
30
+ `footprint` is a boolean array that specifies (implicitly) a
31
+ shape, but also which of the elements within this shape will get
32
+ passed to the filter function. Thus ``size=(n,m)`` is equivalent
33
+ to ``footprint=np.ones((n,m))``. We adjust `size` to the number
34
+ of dimensions of the input array, so that, if the input array is
35
+ shape (10,10,10), and `size` is 2, then the actual size used is
36
+ (2,2,2). When `footprint` is given, `size` is ignored.""")
37
+ _mode_reflect_doc = (
38
+ """mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
39
+ The `mode` parameter determines how the input array is extended
40
+ beyond its boundaries. Default is 'reflect'. Behavior for each valid
41
+ value is as follows:
42
+
43
+ 'reflect' (`d c b a | a b c d | d c b a`)
44
+ The input is extended by reflecting about the edge of the last
45
+ pixel. This mode is also sometimes referred to as half-sample
46
+ symmetric.
47
+
48
+ 'constant' (`k k k k | a b c d | k k k k`)
49
+ The input is extended by filling all values beyond the edge with
50
+ the same constant value, defined by the `cval` parameter.
51
+
52
+ 'nearest' (`a a a a | a b c d | d d d d`)
53
+ The input is extended by replicating the last pixel.
54
+
55
+ 'mirror' (`d c b | a b c d | c b a`)
56
+ The input is extended by reflecting about the center of the last
57
+ pixel. This mode is also sometimes referred to as whole-sample
58
+ symmetric.
59
+
60
+ 'wrap' (`a b c d | a b c d | a b c d`)
61
+ The input is extended by wrapping around to the opposite edge.
62
+
63
+ For consistency with the interpolation functions, the following mode
64
+ names can also be used:
65
+
66
+ 'grid-mirror'
67
+ This is a synonym for 'reflect'.
68
+
69
+ 'grid-constant'
70
+ This is a synonym for 'constant'.
71
+
72
+ 'grid-wrap'
73
+ This is a synonym for 'wrap'.""")
74
+
75
+ _mode_interp_constant_doc = (
76
+ """mode : {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', \
77
+ 'mirror', 'grid-wrap', 'wrap'}, optional
78
+ The `mode` parameter determines how the input array is extended
79
+ beyond its boundaries. Default is 'constant'. Behavior for each valid
80
+ value is as follows (see additional plots and details on
81
+ :ref:`boundary modes <ndimage-interpolation-modes>`):
82
+
83
+ 'reflect' (`d c b a | a b c d | d c b a`)
84
+ The input is extended by reflecting about the edge of the last
85
+ pixel. This mode is also sometimes referred to as half-sample
86
+ symmetric.
87
+
88
+ 'grid-mirror'
89
+ This is a synonym for 'reflect'.
90
+
91
+ 'constant' (`k k k k | a b c d | k k k k`)
92
+ The input is extended by filling all values beyond the edge with
93
+ the same constant value, defined by the `cval` parameter. No
94
+ interpolation is performed beyond the edges of the input.
95
+
96
+ 'grid-constant' (`k k k k | a b c d | k k k k`)
97
+ The input is extended by filling all values beyond the edge with
98
+ the same constant value, defined by the `cval` parameter. Interpolation
99
+ occurs for samples outside the input's extent as well.
100
+
101
+ 'nearest' (`a a a a | a b c d | d d d d`)
102
+ The input is extended by replicating the last pixel.
103
+
104
+ 'mirror' (`d c b | a b c d | c b a`)
105
+ The input is extended by reflecting about the center of the last
106
+ pixel. This mode is also sometimes referred to as whole-sample
107
+ symmetric.
108
+
109
+ 'grid-wrap' (`a b c d | a b c d | a b c d`)
110
+ The input is extended by wrapping around to the opposite edge.
111
+
112
+ 'wrap' (`d b c d | a b c d | b c a b`)
113
+ The input is extended by wrapping around to the opposite edge, but in a
114
+ way such that the last point and initial point exactly overlap. In this
115
+ case it is not well defined which sample will be chosen at the point of
116
+ overlap.""")
117
+ _mode_interp_mirror_doc = (
118
+ _mode_interp_constant_doc.replace("Default is 'constant'",
119
+ "Default is 'mirror'")
120
+ )
121
+ assert _mode_interp_mirror_doc != _mode_interp_constant_doc, \
122
+ 'Default not replaced'
123
+
124
+ _mode_multiple_doc = (
125
+ """mode : str or sequence, optional
126
+ The `mode` parameter determines how the input array is extended
127
+ when the filter overlaps a border. By passing a sequence of modes
128
+ with length equal to the number of dimensions of the input array,
129
+ different modes can be specified along each axis. Default value is
130
+ 'reflect'. The valid values and their behavior is as follows:
131
+
132
+ 'reflect' (`d c b a | a b c d | d c b a`)
133
+ The input is extended by reflecting about the edge of the last
134
+ pixel. This mode is also sometimes referred to as half-sample
135
+ symmetric.
136
+
137
+ 'constant' (`k k k k | a b c d | k k k k`)
138
+ The input is extended by filling all values beyond the edge with
139
+ the same constant value, defined by the `cval` parameter.
140
+
141
+ 'nearest' (`a a a a | a b c d | d d d d`)
142
+ The input is extended by replicating the last pixel.
143
+
144
+ 'mirror' (`d c b | a b c d | c b a`)
145
+ The input is extended by reflecting about the center of the last
146
+ pixel. This mode is also sometimes referred to as whole-sample
147
+ symmetric.
148
+
149
+ 'wrap' (`a b c d | a b c d | a b c d`)
150
+ The input is extended by wrapping around to the opposite edge.
151
+
152
+ For consistency with the interpolation functions, the following mode
153
+ names can also be used:
154
+
155
+ 'grid-constant'
156
+ This is a synonym for 'constant'.
157
+
158
+ 'grid-mirror'
159
+ This is a synonym for 'reflect'.
160
+
161
+ 'grid-wrap'
162
+ This is a synonym for 'wrap'.""")
163
+ _cval_doc = (
164
+ """cval : scalar, optional
165
+ Value to fill past edges of input if `mode` is 'constant'. Default
166
+ is 0.0.""")
167
+ _origin_doc = (
168
+ """origin : int, optional
169
+ Controls the placement of the filter on the input array's pixels.
170
+ A value of 0 (the default) centers the filter over the pixel, with
171
+ positive values shifting the filter to the left, and negative ones
172
+ to the right.""")
173
+ _origin_multiple_doc = (
174
+ """origin : int or sequence, optional
175
+ Controls the placement of the filter on the input array's pixels.
176
+ A value of 0 (the default) centers the filter over the pixel, with
177
+ positive values shifting the filter to the left, and negative ones
178
+ to the right. By passing a sequence of origins with length equal to
179
+ the number of dimensions of the input array, different shifts can
180
+ be specified along each axis.""")
181
+ _extra_arguments_doc = (
182
+ """extra_arguments : sequence, optional
183
+ Sequence of extra positional arguments to pass to passed function.""")
184
+ _extra_keywords_doc = (
185
+ """extra_keywords : dict, optional
186
+ dict of extra keyword arguments to pass to passed function.""")
187
+ _prefilter_doc = (
188
+ """prefilter : bool, optional
189
+ Determines if the input array is prefiltered with `spline_filter`
190
+ before interpolation. The default is True, which will create a
191
+ temporary `float64` array of filtered values if ``order > 1``. If
192
+ setting this to False, the output will be slightly blurred if
193
+ ``order > 1``, unless the input is prefiltered, i.e. it is the result
194
+ of calling `spline_filter` on the original input.""")
195
+
196
+ docdict = {
197
+ 'input': _input_doc,
198
+ 'axis': _axis_doc,
199
+ 'output': _output_doc,
200
+ 'size_foot': _size_foot_doc,
201
+ 'mode_interp_constant': _mode_interp_constant_doc,
202
+ 'mode_interp_mirror': _mode_interp_mirror_doc,
203
+ 'mode_reflect': _mode_reflect_doc,
204
+ 'mode_multiple': _mode_multiple_doc,
205
+ 'cval': _cval_doc,
206
+ 'origin': _origin_doc,
207
+ 'origin_multiple': _origin_multiple_doc,
208
+ 'extra_arguments': _extra_arguments_doc,
209
+ 'extra_keywords': _extra_keywords_doc,
210
+ 'prefilter': _prefilter_doc,
211
+ 'nan': _nan_doc,
212
+ }
213
+
214
+ docfiller: Final = doccer.filldoc(docdict)
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-darwin.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6bebb5ab33670e0f0005e1f058e37d156849a46103bf4dd6a545347e44dbb8c4
3
+ size 188400
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ni_support.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2003-2005 Peter J. Verveer
2
+ #
3
+ # Redistribution and use in source and binary forms, with or without
4
+ # modification, are permitted provided that the following conditions
5
+ # are met:
6
+ #
7
+ # 1. Redistributions of source code must retain the above copyright
8
+ # notice, this list of conditions and the following disclaimer.
9
+ #
10
+ # 2. Redistributions in binary form must reproduce the above
11
+ # copyright notice, this list of conditions and the following
12
+ # disclaimer in the documentation and/or other materials provided
13
+ # with the distribution.
14
+ #
15
+ # 3. The name of the author may not be used to endorse or promote
16
+ # products derived from this software without specific prior
17
+ # written permission.
18
+ #
19
+ # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
20
+ # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21
+ # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
23
+ # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
25
+ # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
27
+ # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28
+ # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29
+ # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
+
31
+ from collections.abc import Iterable
32
+ import operator
33
+ import warnings
34
+ import numpy as np
35
+
36
+
37
+ def _extend_mode_to_code(mode, is_filter=False):
38
+ """Convert an extension mode to the corresponding integer code.
39
+ """
40
+ if mode == 'nearest':
41
+ return 0
42
+ elif mode == 'wrap':
43
+ return 1
44
+ elif mode in ['reflect', 'grid-mirror']:
45
+ return 2
46
+ elif mode == 'mirror':
47
+ return 3
48
+ elif mode == 'constant':
49
+ return 4
50
+ elif mode == 'grid-wrap' and is_filter:
51
+ return 1
52
+ elif mode == 'grid-wrap':
53
+ return 5
54
+ elif mode == 'grid-constant' and is_filter:
55
+ return 4
56
+ elif mode == 'grid-constant':
57
+ return 6
58
+ else:
59
+ raise RuntimeError('boundary mode not supported')
60
+
61
+
62
+ def _normalize_sequence(input, rank):
63
+ """If input is a scalar, create a sequence of length equal to the
64
+ rank by duplicating the input. If input is a sequence,
65
+ check if its length is equal to the length of array.
66
+ """
67
+ is_str = isinstance(input, str)
68
+ if not is_str and np.iterable(input):
69
+ normalized = list(input)
70
+ if len(normalized) != rank:
71
+ err = "sequence argument must have length equal to input rank"
72
+ raise RuntimeError(err)
73
+ else:
74
+ normalized = [input] * rank
75
+ return normalized
76
+
77
+
78
+ def _get_output(output, input, shape=None, complex_output=False):
79
+ if shape is None:
80
+ shape = input.shape
81
+ if output is None:
82
+ if not complex_output:
83
+ output = np.zeros(shape, dtype=input.dtype.name)
84
+ else:
85
+ complex_type = np.promote_types(input.dtype, np.complex64)
86
+ output = np.zeros(shape, dtype=complex_type)
87
+ elif isinstance(output, type | np.dtype):
88
+ # Classes (like `np.float32`) and dtypes are interpreted as dtype
89
+ if complex_output and np.dtype(output).kind != 'c':
90
+ warnings.warn("promoting specified output dtype to complex", stacklevel=3)
91
+ output = np.promote_types(output, np.complex64)
92
+ output = np.zeros(shape, dtype=output)
93
+ elif isinstance(output, str):
94
+ output = np.dtype(output)
95
+ if complex_output and output.kind != 'c':
96
+ raise RuntimeError("output must have complex dtype")
97
+ elif not issubclass(output.type, np.number):
98
+ raise RuntimeError("output must have numeric dtype")
99
+ output = np.zeros(shape, dtype=output)
100
+ else:
101
+ # output was supplied as an array
102
+ output = np.asarray(output)
103
+ if output.shape != shape:
104
+ raise RuntimeError("output shape not correct")
105
+ elif complex_output and output.dtype.kind != 'c':
106
+ raise RuntimeError("output must have complex dtype")
107
+ return output
108
+
109
+
110
+ def _check_axes(axes, ndim):
111
+ if axes is None:
112
+ return tuple(range(ndim))
113
+ elif np.isscalar(axes):
114
+ axes = (operator.index(axes),)
115
+ elif isinstance(axes, Iterable):
116
+ for ax in axes:
117
+ axes = tuple(operator.index(ax) for ax in axes)
118
+ if ax < -ndim or ax > ndim - 1:
119
+ raise ValueError(f"specified axis: {ax} is out of range")
120
+ axes = tuple(ax % ndim if ax < 0 else ax for ax in axes)
121
+ else:
122
+ message = "axes must be an integer, iterable of integers, or None"
123
+ raise ValueError(message)
124
+ if len(tuple(set(axes))) != len(axes):
125
+ raise ValueError("axes must be unique")
126
+ return axes
127
+
128
+ def _skip_if_dtype(arg):
129
+ """'array or dtype' polymorphism.
130
+
131
+ Return None for np.int8, dtype('float32') or 'f' etc
132
+ arg for np.empty(3) etc
133
+ """
134
+ if isinstance(arg, str):
135
+ return None
136
+ if type(arg) is type:
137
+ return None if issubclass(arg, np.generic) else arg
138
+ else:
139
+ return None if isinstance(arg, np.dtype) else arg
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_rank_filter_1d.cpython-312-darwin.so ADDED
Binary file (52.5 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_support_alternative_backends.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ from scipy._lib._array_api import (
3
+ is_cupy, is_jax, scipy_namespace_for, SCIPY_ARRAY_API, xp_capabilities
4
+ )
5
+
6
+ import numpy as np
7
+ from ._ndimage_api import * # noqa: F403
8
+ from . import _ndimage_api
9
+ from . import _delegators
10
+ __all__ = _ndimage_api.__all__
11
+
12
+
13
+ MODULE_NAME = 'ndimage'
14
+
15
+
16
+ def _maybe_convert_arg(arg, xp):
17
+ """Convert arrays/scalars hiding in the sequence `arg`."""
18
+ if isinstance(arg, np.ndarray | np.generic):
19
+ return xp.asarray(arg)
20
+ elif isinstance(arg, list | tuple):
21
+ return type(arg)(_maybe_convert_arg(x, xp) for x in arg)
22
+ else:
23
+ return arg
24
+
25
+
26
+ # Some cupyx.scipy.ndimage functions don't exist or are incompatible with
27
+ # their SciPy counterparts
28
+ CUPY_BLOCKLIST = [
29
+ 'distance_transform_bf',
30
+ 'distance_transform_cdt',
31
+ 'find_objects',
32
+ 'geometric_transform',
33
+ 'vectorized_filter',
34
+ ]
35
+
36
+
37
+ def delegate_xp(delegator, module_name):
38
+ def inner(func):
39
+ @functools.wraps(func)
40
+ def wrapper(*args, **kwds):
41
+ xp = delegator(*args, **kwds)
42
+
43
+ # try delegating to a cupyx/jax namesake
44
+ if is_cupy(xp) and func.__name__ not in CUPY_BLOCKLIST:
45
+ # https://github.com/cupy/cupy/issues/8336
46
+ import importlib
47
+ cupyx_module = importlib.import_module(f"cupyx.scipy.{module_name}")
48
+ cupyx_func = getattr(cupyx_module, func.__name__)
49
+ return cupyx_func(*args, **kwds)
50
+ elif is_jax(xp) and func.__name__ == "map_coordinates":
51
+ spx = scipy_namespace_for(xp)
52
+ jax_module = getattr(spx, module_name)
53
+ jax_func = getattr(jax_module, func.__name__)
54
+ return jax_func(*args, **kwds)
55
+ else:
56
+ # the original function (does all np.asarray internally)
57
+ # XXX: output arrays
58
+ result = func(*args, **kwds)
59
+
60
+ if isinstance(result, np.ndarray | np.generic):
61
+ # XXX: np.int32->np.array_0D
62
+ return xp.asarray(result)
63
+ elif isinstance(result, int):
64
+ return result
65
+ elif isinstance(result, dict):
66
+ # value_indices:
67
+ # result is {np.int64(1): (array(0), array(1))} etc
68
+ return {
69
+ k.item(): tuple(xp.asarray(vv) for vv in v)
70
+ for k,v in result.items()
71
+ }
72
+ elif result is None:
73
+ # inplace operations
74
+ return result
75
+ else:
76
+ # lists/tuples
77
+ return _maybe_convert_arg(result, xp)
78
+ return wrapper
79
+ return inner
80
+
81
+ default_capabilities = xp_capabilities(
82
+ cpu_only=True, exceptions=["cupy"], allow_dask_compute=True, jax_jit=False
83
+ )
84
+
85
+ capabilities_dict = {
86
+ "geometric_transform": xp_capabilities(
87
+ cpu_only=True, allow_dask_compute=True, jax_jit=False
88
+ ),
89
+ "find_objects": xp_capabilities(
90
+ cpu_only=True, allow_dask_compute=True, jax_jit=False
91
+ ),
92
+ "distance_transform_bf": xp_capabilities(
93
+ cpu_only=True, allow_dask_compute=True, jax_jit=False
94
+ ),
95
+ "distance_transform_cdt": xp_capabilities(
96
+ cpu_only=True, allow_dask_compute=True, jax_jit=False
97
+ ),
98
+ "vectorized_filter": xp_capabilities(
99
+ cpu_only=True, allow_dask_compute=True, jax_jit=False
100
+ ),
101
+ "generate_binary_structure": xp_capabilities(out_of_scope=True),
102
+ "map_coordinates": xp_capabilities(
103
+ cpu_only=True, exceptions=["cupy", "jax.numpy"],
104
+ allow_dask_compute=True, jax_jit=True
105
+ )
106
+ }
107
+
108
+ # ### decorate ###
109
+ for func_name in _ndimage_api.__all__:
110
+ bare_func = getattr(_ndimage_api, func_name)
111
+ delegator = getattr(_delegators, func_name + "_signature")
112
+
113
+ capabilities = capabilities_dict.get(func_name, default_capabilities)
114
+
115
+ f = capabilities(
116
+ delegate_xp(delegator, MODULE_NAME)(bare_func)
117
+ if SCIPY_ARRAY_API else bare_func
118
+ )
119
+ # add the decorated function to the namespace, to be imported in __init__.py
120
+ vars()[func_name] = f
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/filters.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.ndimage` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = [ # noqa: F822
9
+ 'correlate1d', 'convolve1d', 'gaussian_filter1d',
10
+ 'gaussian_filter', 'prewitt', 'sobel', 'generic_laplace',
11
+ 'laplace', 'gaussian_laplace', 'generic_gradient_magnitude',
12
+ 'gaussian_gradient_magnitude', 'correlate', 'convolve',
13
+ 'uniform_filter1d', 'uniform_filter', 'minimum_filter1d',
14
+ 'maximum_filter1d', 'minimum_filter', 'maximum_filter',
15
+ 'rank_filter', 'median_filter', 'percentile_filter',
16
+ 'generic_filter1d', 'generic_filter'
17
+ ]
18
+
19
+
20
+ def __dir__():
21
+ return __all__
22
+
23
+
24
+ def __getattr__(name):
25
+ return _sub_module_deprecation(sub_package='ndimage', module='filters',
26
+ private_modules=['_filters'], all=__all__,
27
+ attribute=name)
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/fourier.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.ndimage` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = [ # noqa: F822
9
+ 'fourier_gaussian', 'fourier_uniform',
10
+ 'fourier_ellipsoid', 'fourier_shift'
11
+ ]
12
+
13
+
14
+ def __dir__():
15
+ return __all__
16
+
17
+
18
+ def __getattr__(name):
19
+ return _sub_module_deprecation(sub_package='ndimage', module='fourier',
20
+ private_modules=['_fourier'], all=__all__,
21
+ attribute=name)
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/interpolation.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.ndimage` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = [ # noqa: F822
9
+ 'spline_filter1d', 'spline_filter',
10
+ 'geometric_transform', 'map_coordinates',
11
+ 'affine_transform', 'shift', 'zoom', 'rotate',
12
+ ]
13
+
14
+
15
+ def __dir__():
16
+ return __all__
17
+
18
+
19
+ def __getattr__(name):
20
+ return _sub_module_deprecation(sub_package='ndimage', module='interpolation',
21
+ private_modules=['_interpolation'], all=__all__,
22
+ attribute=name)
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/measurements.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.ndimage` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = [ # noqa: F822
9
+ 'label', 'find_objects', 'labeled_comprehension',
10
+ 'sum', 'mean', 'variance', 'standard_deviation',
11
+ 'minimum', 'maximum', 'median', 'minimum_position',
12
+ 'maximum_position', 'extrema', 'center_of_mass',
13
+ 'histogram', 'watershed_ift', 'sum_labels'
14
+ ]
15
+
16
+
17
+ def __dir__():
18
+ return __all__
19
+
20
+
21
+ def __getattr__(name):
22
+ return _sub_module_deprecation(sub_package='ndimage', module='measurements',
23
+ private_modules=['_measurements'], all=__all__,
24
+ attribute=name)
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/morphology.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.ndimage` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = [ # noqa: F822
9
+ 'iterate_structure', 'generate_binary_structure',
10
+ 'binary_erosion', 'binary_dilation', 'binary_opening',
11
+ 'binary_closing', 'binary_hit_or_miss', 'binary_propagation',
12
+ 'binary_fill_holes', 'grey_erosion', 'grey_dilation',
13
+ 'grey_opening', 'grey_closing', 'morphological_gradient',
14
+ 'morphological_laplace', 'white_tophat', 'black_tophat',
15
+ 'distance_transform_bf', 'distance_transform_cdt',
16
+ 'distance_transform_edt'
17
+ ]
18
+
19
+
20
+ def __dir__():
21
+ return __all__
22
+
23
+
24
+ def __getattr__(name):
25
+ return _sub_module_deprecation(sub_package='ndimage', module='morphology',
26
+ private_modules=['_morphology'], all=__all__,
27
+ attribute=name)
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/.___init__.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/.___pycache__ ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._data ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._dots.png ADDED

Git LFS Details

  • SHA256: fbd1f4c19356c9f782c0fce50a927d08f5a7a89ae88cc56fe8e671aeba8ef15d
  • Pointer size: 129 Bytes
  • Size of remote file: 4.1 kB
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_c_api.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_datatypes.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_filters.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_fourier.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_interpolation.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_measurements.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_morphology.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_ni_support.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_splines.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ # list of numarray data types
4
+ integer_types: list[str] = [
5
+ "int8", "uint8", "int16", "uint16",
6
+ "int32", "uint32", "int64", "uint64"]
7
+
8
+ float_types: list[str] = ["float32", "float64"]
9
+
10
+ complex_types: list[str] = ["complex64", "complex128"]
11
+
12
+ types: list[str] = integer_types + float_types
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/._label_inputs.txt ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/._label_results.txt ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/._label_strels.txt ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_inputs.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 1 1 1 1 1 1 1
2
+ 1 1 1 1 1 1 1
3
+ 1 1 1 1 1 1 1
4
+ 1 1 1 1 1 1 1
5
+ 1 1 1 1 1 1 1
6
+ 1 1 1 1 1 1 1
7
+ 1 1 1 1 1 1 1
8
+ 1 1 1 0 1 1 1
9
+ 1 1 0 0 0 1 1
10
+ 1 0 1 0 1 0 1
11
+ 0 0 0 1 0 0 0
12
+ 1 0 1 0 1 0 1
13
+ 1 1 0 0 0 1 1
14
+ 1 1 1 0 1 1 1
15
+ 1 0 1 1 1 0 1
16
+ 0 0 0 1 0 0 0
17
+ 1 0 0 1 0 0 1
18
+ 1 1 1 1 1 1 1
19
+ 1 0 0 1 0 0 1
20
+ 0 0 0 1 0 0 0
21
+ 1 0 1 1 1 0 1
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_results.txt ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 1 1 1 1 1 1 1
2
+ 1 1 1 1 1 1 1
3
+ 1 1 1 1 1 1 1
4
+ 1 1 1 1 1 1 1
5
+ 1 1 1 1 1 1 1
6
+ 1 1 1 1 1 1 1
7
+ 1 1 1 1 1 1 1
8
+ 1 1 1 1 1 1 1
9
+ 1 1 1 1 1 1 1
10
+ 1 1 1 1 1 1 1
11
+ 1 1 1 1 1 1 1
12
+ 1 1 1 1 1 1 1
13
+ 1 1 1 1 1 1 1
14
+ 1 1 1 1 1 1 1
15
+ 1 1 1 1 1 1 1
16
+ 2 2 2 2 2 2 2
17
+ 3 3 3 3 3 3 3
18
+ 4 4 4 4 4 4 4
19
+ 5 5 5 5 5 5 5
20
+ 6 6 6 6 6 6 6
21
+ 7 7 7 7 7 7 7
22
+ 1 1 1 1 1 1 1
23
+ 1 1 1 1 1 1 1
24
+ 1 1 1 1 1 1 1
25
+ 1 1 1 1 1 1 1
26
+ 1 1 1 1 1 1 1
27
+ 1 1 1 1 1 1 1
28
+ 1 1 1 1 1 1 1
29
+ 1 2 3 4 5 6 7
30
+ 8 9 10 11 12 13 14
31
+ 15 16 17 18 19 20 21
32
+ 22 23 24 25 26 27 28
33
+ 29 30 31 32 33 34 35
34
+ 36 37 38 39 40 41 42
35
+ 43 44 45 46 47 48 49
36
+ 1 1 1 1 1 1 1
37
+ 1 1 1 1 1 1 1
38
+ 1 1 1 1 1 1 1
39
+ 1 1 1 1 1 1 1
40
+ 1 1 1 1 1 1 1
41
+ 1 1 1 1 1 1 1
42
+ 1 1 1 1 1 1 1
43
+ 1 1 1 1 1 1 1
44
+ 1 1 1 1 1 1 1
45
+ 1 1 1 1 1 1 1
46
+ 1 1 1 1 1 1 1
47
+ 1 1 1 1 1 1 1
48
+ 1 1 1 1 1 1 1
49
+ 1 1 1 1 1 1 1
50
+ 1 2 3 4 5 6 7
51
+ 8 1 2 3 4 5 6
52
+ 9 8 1 2 3 4 5
53
+ 10 9 8 1 2 3 4
54
+ 11 10 9 8 1 2 3
55
+ 12 11 10 9 8 1 2
56
+ 13 12 11 10 9 8 1
57
+ 1 2 3 4 5 6 7
58
+ 1 2 3 4 5 6 7
59
+ 1 2 3 4 5 6 7
60
+ 1 2 3 4 5 6 7
61
+ 1 2 3 4 5 6 7
62
+ 1 2 3 4 5 6 7
63
+ 1 2 3 4 5 6 7
64
+ 1 1 1 1 1 1 1
65
+ 1 1 1 1 1 1 1
66
+ 1 1 1 1 1 1 1
67
+ 1 1 1 1 1 1 1
68
+ 1 1 1 1 1 1 1
69
+ 1 1 1 1 1 1 1
70
+ 1 1 1 1 1 1 1
71
+ 1 1 1 1 1 1 1
72
+ 1 1 1 1 1 1 1
73
+ 1 1 1 1 1 1 1
74
+ 1 1 1 1 1 1 1
75
+ 1 1 1 1 1 1 1
76
+ 1 1 1 1 1 1 1
77
+ 1 1 1 1 1 1 1
78
+ 1 2 1 2 1 2 1
79
+ 2 1 2 1 2 1 2
80
+ 1 2 1 2 1 2 1
81
+ 2 1 2 1 2 1 2
82
+ 1 2 1 2 1 2 1
83
+ 2 1 2 1 2 1 2
84
+ 1 2 1 2 1 2 1
85
+ 1 2 3 4 5 6 7
86
+ 2 3 4 5 6 7 8
87
+ 3 4 5 6 7 8 9
88
+ 4 5 6 7 8 9 10
89
+ 5 6 7 8 9 10 11
90
+ 6 7 8 9 10 11 12
91
+ 7 8 9 10 11 12 13
92
+ 1 1 1 1 1 1 1
93
+ 1 1 1 1 1 1 1
94
+ 1 1 1 1 1 1 1
95
+ 1 1 1 1 1 1 1
96
+ 1 1 1 1 1 1 1
97
+ 1 1 1 1 1 1 1
98
+ 1 1 1 1 1 1 1
99
+ 1 1 1 0 2 2 2
100
+ 1 1 0 0 0 2 2
101
+ 1 0 3 0 2 0 4
102
+ 0 0 0 2 0 0 0
103
+ 5 0 2 0 6 0 7
104
+ 2 2 0 0 0 7 7
105
+ 2 2 2 0 7 7 7
106
+ 1 1 1 0 2 2 2
107
+ 1 1 0 0 0 2 2
108
+ 3 0 1 0 4 0 2
109
+ 0 0 0 1 0 0 0
110
+ 5 0 6 0 1 0 7
111
+ 5 5 0 0 0 1 1
112
+ 5 5 5 0 1 1 1
113
+ 1 1 1 0 2 2 2
114
+ 3 3 0 0 0 4 4
115
+ 5 0 6 0 7 0 8
116
+ 0 0 0 9 0 0 0
117
+ 10 0 11 0 12 0 13
118
+ 14 14 0 0 0 15 15
119
+ 16 16 16 0 17 17 17
120
+ 1 1 1 0 2 3 3
121
+ 1 1 0 0 0 3 3
122
+ 1 0 4 0 3 0 3
123
+ 0 0 0 3 0 0 0
124
+ 3 0 3 0 5 0 6
125
+ 3 3 0 0 0 6 6
126
+ 3 3 7 0 6 6 6
127
+ 1 2 3 0 4 5 6
128
+ 7 8 0 0 0 9 10
129
+ 11 0 12 0 13 0 14
130
+ 0 0 0 15 0 0 0
131
+ 16 0 17 0 18 0 19
132
+ 20 21 0 0 0 22 23
133
+ 24 25 26 0 27 28 29
134
+ 1 1 1 0 2 2 2
135
+ 1 1 0 0 0 2 2
136
+ 1 0 3 0 2 0 2
137
+ 0 0 0 2 0 0 0
138
+ 2 0 2 0 4 0 5
139
+ 2 2 0 0 0 5 5
140
+ 2 2 2 0 5 5 5
141
+ 1 1 1 0 2 2 2
142
+ 1 1 0 0 0 2 2
143
+ 1 0 3 0 4 0 2
144
+ 0 0 0 5 0 0 0
145
+ 6 0 7 0 8 0 9
146
+ 6 6 0 0 0 9 9
147
+ 6 6 6 0 9 9 9
148
+ 1 2 3 0 4 5 6
149
+ 7 1 0 0 0 4 5
150
+ 8 0 1 0 9 0 4
151
+ 0 0 0 1 0 0 0
152
+ 10 0 11 0 1 0 12
153
+ 13 10 0 0 0 1 14
154
+ 15 13 10 0 16 17 1
155
+ 1 2 3 0 4 5 6
156
+ 1 2 0 0 0 5 6
157
+ 1 0 7 0 8 0 6
158
+ 0 0 0 9 0 0 0
159
+ 10 0 11 0 12 0 13
160
+ 10 14 0 0 0 15 13
161
+ 10 14 16 0 17 15 13
162
+ 1 1 1 0 1 1 1
163
+ 1 1 0 0 0 1 1
164
+ 1 0 1 0 1 0 1
165
+ 0 0 0 1 0 0 0
166
+ 1 0 1 0 1 0 1
167
+ 1 1 0 0 0 1 1
168
+ 1 1 1 0 1 1 1
169
+ 1 1 2 0 3 3 3
170
+ 1 1 0 0 0 3 3
171
+ 1 0 1 0 4 0 3
172
+ 0 0 0 1 0 0 0
173
+ 5 0 6 0 1 0 1
174
+ 5 5 0 0 0 1 1
175
+ 5 5 5 0 7 1 1
176
+ 1 2 1 0 1 3 1
177
+ 2 1 0 0 0 1 3
178
+ 1 0 1 0 1 0 1
179
+ 0 0 0 1 0 0 0
180
+ 1 0 1 0 1 0 1
181
+ 4 1 0 0 0 1 5
182
+ 1 4 1 0 1 5 1
183
+ 1 2 3 0 4 5 6
184
+ 2 3 0 0 0 6 7
185
+ 3 0 8 0 6 0 9
186
+ 0 0 0 6 0 0 0
187
+ 10 0 6 0 11 0 12
188
+ 13 6 0 0 0 12 14
189
+ 6 15 16 0 12 14 17
190
+ 1 1 1 0 2 2 2
191
+ 1 1 0 0 0 2 2
192
+ 1 0 1 0 3 0 2
193
+ 0 0 0 1 0 0 0
194
+ 4 0 5 0 1 0 1
195
+ 4 4 0 0 0 1 1
196
+ 4 4 4 0 1 1 1
197
+ 1 0 2 2 2 0 3
198
+ 0 0 0 2 0 0 0
199
+ 4 0 0 5 0 0 5
200
+ 5 5 5 5 5 5 5
201
+ 5 0 0 5 0 0 6
202
+ 0 0 0 7 0 0 0
203
+ 8 0 7 7 7 0 9
204
+ 1 0 2 2 2 0 3
205
+ 0 0 0 2 0 0 0
206
+ 4 0 0 4 0 0 5
207
+ 4 4 4 4 4 4 4
208
+ 6 0 0 4 0 0 4
209
+ 0 0 0 7 0 0 0
210
+ 8 0 7 7 7 0 9
211
+ 1 0 2 2 2 0 3
212
+ 0 0 0 4 0 0 0
213
+ 5 0 0 6 0 0 7
214
+ 8 8 8 8 8 8 8
215
+ 9 0 0 10 0 0 11
216
+ 0 0 0 12 0 0 0
217
+ 13 0 14 14 14 0 15
218
+ 1 0 2 3 3 0 4
219
+ 0 0 0 3 0 0 0
220
+ 5 0 0 3 0 0 6
221
+ 5 5 3 3 3 6 6
222
+ 5 0 0 3 0 0 6
223
+ 0 0 0 3 0 0 0
224
+ 7 0 3 3 8 0 9
225
+ 1 0 2 3 4 0 5
226
+ 0 0 0 6 0 0 0
227
+ 7 0 0 8 0 0 9
228
+ 10 11 12 13 14 15 16
229
+ 17 0 0 18 0 0 19
230
+ 0 0 0 20 0 0 0
231
+ 21 0 22 23 24 0 25
232
+ 1 0 2 2 2 0 3
233
+ 0 0 0 2 0 0 0
234
+ 2 0 0 2 0 0 2
235
+ 2 2 2 2 2 2 2
236
+ 2 0 0 2 0 0 2
237
+ 0 0 0 2 0 0 0
238
+ 4 0 2 2 2 0 5
239
+ 1 0 2 2 2 0 3
240
+ 0 0 0 2 0 0 0
241
+ 2 0 0 2 0 0 2
242
+ 2 2 2 2 2 2 2
243
+ 2 0 0 2 0 0 2
244
+ 0 0 0 2 0 0 0
245
+ 4 0 2 2 2 0 5
246
+ 1 0 2 3 4 0 5
247
+ 0 0 0 2 0 0 0
248
+ 6 0 0 7 0 0 8
249
+ 9 6 10 11 7 12 13
250
+ 14 0 0 10 0 0 12
251
+ 0 0 0 15 0 0 0
252
+ 16 0 17 18 15 0 19
253
+ 1 0 2 3 4 0 5
254
+ 0 0 0 3 0 0 0
255
+ 6 0 0 3 0 0 7
256
+ 6 8 9 3 10 11 7
257
+ 6 0 0 3 0 0 7
258
+ 0 0 0 3 0 0 0
259
+ 12 0 13 3 14 0 15
260
+ 1 0 2 2 2 0 3
261
+ 0 0 0 2 0 0 0
262
+ 2 0 0 2 0 0 2
263
+ 2 2 2 2 2 2 2
264
+ 2 0 0 2 0 0 2
265
+ 0 0 0 2 0 0 0
266
+ 4 0 2 2 2 0 5
267
+ 1 0 2 2 3 0 4
268
+ 0 0 0 2 0 0 0
269
+ 5 0 0 2 0 0 6
270
+ 5 5 2 2 2 6 6
271
+ 5 0 0 2 0 0 6
272
+ 0 0 0 2 0 0 0
273
+ 7 0 8 2 2 0 9
274
+ 1 0 2 3 2 0 4
275
+ 0 0 0 2 0 0 0
276
+ 5 0 0 6 0 0 7
277
+ 8 5 6 9 6 7 10
278
+ 5 0 0 6 0 0 7
279
+ 0 0 0 11 0 0 0
280
+ 12 0 11 13 11 0 14
281
+ 1 0 2 3 4 0 5
282
+ 0 0 0 4 0 0 0
283
+ 6 0 0 7 0 0 8
284
+ 9 10 7 11 12 8 13
285
+ 10 0 0 12 0 0 14
286
+ 0 0 0 15 0 0 0
287
+ 16 0 15 17 18 0 19
288
+ 1 0 2 2 2 0 3
289
+ 0 0 0 2 0 0 0
290
+ 2 0 0 2 0 0 2
291
+ 2 2 2 2 2 2 2
292
+ 2 0 0 2 0 0 2
293
+ 0 0 0 2 0 0 0
294
+ 4 0 2 2 2 0 5
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_strels.txt ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 0 0 1
2
+ 1 1 1
3
+ 1 0 0
4
+ 1 0 0
5
+ 1 1 1
6
+ 0 0 1
7
+ 0 0 0
8
+ 1 1 1
9
+ 0 0 0
10
+ 0 1 1
11
+ 0 1 0
12
+ 1 1 0
13
+ 0 0 0
14
+ 0 0 0
15
+ 0 0 0
16
+ 0 1 1
17
+ 1 1 1
18
+ 1 1 0
19
+ 0 1 0
20
+ 1 1 1
21
+ 0 1 0
22
+ 1 0 0
23
+ 0 1 0
24
+ 0 0 1
25
+ 0 1 0
26
+ 0 1 0
27
+ 0 1 0
28
+ 1 1 1
29
+ 1 1 1
30
+ 1 1 1
31
+ 1 1 0
32
+ 0 1 0
33
+ 0 1 1
34
+ 1 0 1
35
+ 0 1 0
36
+ 1 0 1
37
+ 0 0 1
38
+ 0 1 0
39
+ 1 0 0
40
+ 1 1 0
41
+ 1 1 1
42
+ 0 1 1
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/dots.png ADDED

Git LFS Details

  • SHA256: b20b56fadc7471c0694d3e8148d9e28a83d7967bac16bf8852094afea3950414
  • Pointer size: 129 Bytes
  • Size of remote file: 2.11 kB
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_c_api.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy._lib._array_api import xp_assert_close
3
+
4
+ from scipy import ndimage
5
+ from scipy.ndimage import _ctest
6
+ from scipy.ndimage import _cytest
7
+ from scipy._lib._ccallback import LowLevelCallable
8
+
9
+ FILTER1D_FUNCTIONS = [
10
+ lambda filter_size: _ctest.filter1d(filter_size),
11
+ lambda filter_size: _cytest.filter1d(filter_size, with_signature=False),
12
+ lambda filter_size: LowLevelCallable(
13
+ _cytest.filter1d(filter_size, with_signature=True)
14
+ ),
15
+ lambda filter_size: LowLevelCallable.from_cython(
16
+ _cytest, "_filter1d",
17
+ _cytest.filter1d_capsule(filter_size),
18
+ ),
19
+ ]
20
+
21
+ FILTER2D_FUNCTIONS = [
22
+ lambda weights: _ctest.filter2d(weights),
23
+ lambda weights: _cytest.filter2d(weights, with_signature=False),
24
+ lambda weights: LowLevelCallable(_cytest.filter2d(weights, with_signature=True)),
25
+ lambda weights: LowLevelCallable.from_cython(_cytest,
26
+ "_filter2d",
27
+ _cytest.filter2d_capsule(weights),),
28
+ ]
29
+
30
+ TRANSFORM_FUNCTIONS = [
31
+ lambda shift: _ctest.transform(shift),
32
+ lambda shift: _cytest.transform(shift, with_signature=False),
33
+ lambda shift: LowLevelCallable(_cytest.transform(shift, with_signature=True)),
34
+ lambda shift: LowLevelCallable.from_cython(_cytest,
35
+ "_transform",
36
+ _cytest.transform_capsule(shift),),
37
+ ]
38
+
39
+
40
+ def test_generic_filter():
41
+ def filter2d(footprint_elements, weights):
42
+ return (weights*footprint_elements).sum()
43
+
44
+ def check(j):
45
+ func = FILTER2D_FUNCTIONS[j]
46
+
47
+ im = np.ones((20, 20))
48
+ im[:10,:10] = 0
49
+ footprint = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])
50
+ footprint_size = np.count_nonzero(footprint)
51
+ weights = np.ones(footprint_size)/footprint_size
52
+
53
+ res = ndimage.generic_filter(im, func(weights),
54
+ footprint=footprint)
55
+ std = ndimage.generic_filter(im, filter2d, footprint=footprint,
56
+ extra_arguments=(weights,))
57
+ xp_assert_close(res, std, err_msg=f"#{j} failed")
58
+
59
+ for j, func in enumerate(FILTER2D_FUNCTIONS):
60
+ check(j)
61
+
62
+
63
+ def test_generic_filter1d():
64
+ def filter1d(input_line, output_line, filter_size):
65
+ for i in range(output_line.size):
66
+ output_line[i] = 0
67
+ for j in range(filter_size):
68
+ output_line[i] += input_line[i+j]
69
+ output_line /= filter_size
70
+
71
+ def check(j):
72
+ func = FILTER1D_FUNCTIONS[j]
73
+
74
+ im = np.tile(np.hstack((np.zeros(10), np.ones(10))), (10, 1))
75
+ filter_size = 3
76
+
77
+ res = ndimage.generic_filter1d(im, func(filter_size),
78
+ filter_size)
79
+ std = ndimage.generic_filter1d(im, filter1d, filter_size,
80
+ extra_arguments=(filter_size,))
81
+ xp_assert_close(res, std, err_msg=f"#{j} failed")
82
+
83
+ for j, func in enumerate(FILTER1D_FUNCTIONS):
84
+ check(j)
85
+
86
+
87
+ def test_geometric_transform():
88
+ def transform(output_coordinates, shift):
89
+ return output_coordinates[0] - shift, output_coordinates[1] - shift
90
+
91
+ def check(j):
92
+ func = TRANSFORM_FUNCTIONS[j]
93
+
94
+ im = np.arange(12).reshape(4, 3).astype(np.float64)
95
+ shift = 0.5
96
+
97
+ res = ndimage.geometric_transform(im, func(shift))
98
+ std = ndimage.geometric_transform(im, transform, extra_arguments=(shift,))
99
+ xp_assert_close(res, std, err_msg=f"#{j} failed")
100
+
101
+ for j, func in enumerate(TRANSFORM_FUNCTIONS):
102
+ check(j)
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_datatypes.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Testing data types for ndimage calls
2
+ """
3
+ import numpy as np
4
+
5
+ from scipy._lib._array_api import assert_array_almost_equal
6
+ import pytest
7
+
8
+ from scipy import ndimage
9
+
10
+
11
+ def test_map_coordinates_dts():
12
+ # check that ndimage accepts different data types for interpolation
13
+ data = np.array([[4, 1, 3, 2],
14
+ [7, 6, 8, 5],
15
+ [3, 5, 3, 6]])
16
+ shifted_data = np.array([[0, 0, 0, 0],
17
+ [0, 4, 1, 3],
18
+ [0, 7, 6, 8]])
19
+ idx = np.indices(data.shape)
20
+ dts = (np.uint8, np.uint16, np.uint32, np.uint64,
21
+ np.int8, np.int16, np.int32, np.int64,
22
+ np.intp, np.uintp, np.float32, np.float64)
23
+ for order in range(0, 6):
24
+ for data_dt in dts:
25
+ these_data = data.astype(data_dt)
26
+ for coord_dt in dts:
27
+ # affine mapping
28
+ mat = np.eye(2, dtype=coord_dt)
29
+ off = np.zeros((2,), dtype=coord_dt)
30
+ out = ndimage.affine_transform(these_data, mat, off)
31
+ assert_array_almost_equal(these_data, out)
32
+ # map coordinates
33
+ coords_m1 = idx.astype(coord_dt) - 1
34
+ coords_p10 = idx.astype(coord_dt) + 10
35
+ out = ndimage.map_coordinates(these_data, coords_m1, order=order)
36
+ assert_array_almost_equal(out, shifted_data)
37
+ # check constant fill works
38
+ out = ndimage.map_coordinates(these_data, coords_p10, order=order)
39
+ assert_array_almost_equal(out, np.zeros((3,4)))
40
+ # check shift and zoom
41
+ out = ndimage.shift(these_data, 1)
42
+ assert_array_almost_equal(out, shifted_data)
43
+ out = ndimage.zoom(these_data, 1)
44
+ assert_array_almost_equal(these_data, out)
45
+
46
+
47
+ @pytest.mark.xfail(True, reason="Broken on many platforms")
48
+ def test_uint64_max():
49
+ # Test interpolation respects uint64 max. Reported to fail at least on
50
+ # win32 (due to the 32 bit visual C compiler using signed int64 when
51
+ # converting between uint64 to double) and Debian on s390x.
52
+ # Interpolation is always done in double precision floating point, so
53
+ # we use the largest uint64 value for which int(float(big)) still fits
54
+ # in a uint64.
55
+ # This test was last enabled on macOS only, and there it started failing
56
+ # on arm64 as well (see gh-19117).
57
+ big = 2**64 - 1025
58
+ arr = np.array([big, big, big], dtype=np.uint64)
59
+ # Tests geometric transform (map_coordinates, affine_transform)
60
+ inds = np.indices(arr.shape) - 0.1
61
+ x = ndimage.map_coordinates(arr, inds)
62
+ assert x[1] == int(float(big))
63
+ assert x[2] == int(float(big))
64
+ # Tests zoom / shift
65
+ x = ndimage.shift(arr, 0.1)
66
+ assert x[1] == int(float(big))
67
+ assert x[2] == int(float(big))
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_filters.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_fourier.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numpy as np
3
+
4
+ from scipy._lib._array_api import (
5
+ xp_assert_equal,
6
+ assert_array_almost_equal,
7
+ assert_almost_equal,
8
+ is_cupy,
9
+ make_xp_test_case,
10
+ make_xp_pytest_param,
11
+ )
12
+
13
+ import pytest
14
+
15
+ from scipy import ndimage
16
+
17
+ skip_xp_backends = pytest.mark.skip_xp_backends
18
+
19
+
20
+ class TestNdimageFourier:
21
+
22
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
23
+ @pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)])
24
+ @make_xp_test_case(ndimage.fourier_gaussian)
25
+ def test_fourier_gaussian_real01(self, shape, dtype, dec, xp):
26
+ fft = getattr(xp, 'fft')
27
+
28
+ a = np.zeros(shape, dtype=dtype)
29
+ a[0, 0] = 1.0
30
+ a = xp.asarray(a)
31
+
32
+ a = fft.rfft(a, n=shape[0], axis=0)
33
+ a = fft.fft(a, n=shape[1], axis=1)
34
+ a = ndimage.fourier_gaussian(a, [5.0, 2.5], shape[0], 0)
35
+ a = fft.ifft(a, n=shape[1], axis=1)
36
+ a = fft.irfft(a, n=shape[0], axis=0)
37
+ assert_almost_equal(ndimage.sum(a), xp.asarray(1), decimal=dec,
38
+ check_0d=False)
39
+
40
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
41
+ @pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)])
42
+ @make_xp_test_case(ndimage.fourier_gaussian)
43
+ def test_fourier_gaussian_complex01(self, shape, dtype, dec, xp):
44
+ fft = getattr(xp, 'fft')
45
+
46
+ a = np.zeros(shape, dtype=dtype)
47
+ a[0, 0] = 1.0
48
+ a = xp.asarray(a)
49
+
50
+ a = fft.fft(a, n=shape[0], axis=0)
51
+ a = fft.fft(a, n=shape[1], axis=1)
52
+ a = ndimage.fourier_gaussian(a, [5.0, 2.5], -1, 0)
53
+ a = fft.ifft(a, n=shape[1], axis=1)
54
+ a = fft.ifft(a, n=shape[0], axis=0)
55
+ assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
56
+ check_0d=False)
57
+
58
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
59
+ @pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)])
60
+ @make_xp_test_case(ndimage.fourier_uniform)
61
+ def test_fourier_uniform_real01(self, shape, dtype, dec, xp):
62
+ fft = getattr(xp, 'fft')
63
+
64
+ a = np.zeros(shape, dtype=dtype)
65
+ a[0, 0] = 1.0
66
+ a = xp.asarray(a)
67
+
68
+ a = fft.rfft(a, n=shape[0], axis=0)
69
+ a = fft.fft(a, n=shape[1], axis=1)
70
+ a = ndimage.fourier_uniform(a, [5.0, 2.5], shape[0], 0)
71
+ a = fft.ifft(a, n=shape[1], axis=1)
72
+ a = fft.irfft(a, n=shape[0], axis=0)
73
+ assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec,
74
+ check_0d=False)
75
+
76
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
77
+ @pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)])
78
+ @make_xp_test_case(ndimage.fourier_uniform)
79
+ def test_fourier_uniform_complex01(self, shape, dtype, dec, xp):
80
+ fft = getattr(xp, 'fft')
81
+
82
+ a = np.zeros(shape, dtype=dtype)
83
+ a[0, 0] = 1.0
84
+ a = xp.asarray(a)
85
+
86
+ a = fft.fft(a, n=shape[0], axis=0)
87
+ a = fft.fft(a, n=shape[1], axis=1)
88
+ a = ndimage.fourier_uniform(a, [5.0, 2.5], -1, 0)
89
+ a = fft.ifft(a, n=shape[1], axis=1)
90
+ a = fft.ifft(a, n=shape[0], axis=0)
91
+ assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
92
+ check_0d=False)
93
+
94
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
95
+ @pytest.mark.parametrize('dtype, dec', [("float32", 4), ("float64", 11)])
96
+ @make_xp_test_case(ndimage.fourier_shift)
97
+ def test_fourier_shift_real01(self, shape, dtype, dec, xp):
98
+ fft = getattr(xp, 'fft')
99
+
100
+ expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
101
+ expected = xp.asarray(expected)
102
+
103
+ a = fft.rfft(expected, n=shape[0], axis=0)
104
+ a = fft.fft(a, n=shape[1], axis=1)
105
+ a = ndimage.fourier_shift(a, [1, 1], shape[0], 0)
106
+ a = fft.ifft(a, n=shape[1], axis=1)
107
+ a = fft.irfft(a, n=shape[0], axis=0)
108
+ assert_array_almost_equal(a[1:, 1:], expected[:-1, :-1], decimal=dec)
109
+
110
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
111
+ @pytest.mark.parametrize('dtype, dec', [("complex64", 4), ("complex128", 11)])
112
+ @make_xp_test_case(ndimage.fourier_shift)
113
+ def test_fourier_shift_complex01(self, shape, dtype, dec, xp):
114
+ fft = getattr(xp, 'fft')
115
+
116
+ expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
117
+ expected = xp.asarray(expected)
118
+
119
+ a = fft.fft(expected, n=shape[0], axis=0)
120
+ a = fft.fft(a, n=shape[1], axis=1)
121
+ a = ndimage.fourier_shift(a, [1, 1], -1, 0)
122
+ a = fft.ifft(a, n=shape[1], axis=1)
123
+ a = fft.ifft(a, n=shape[0], axis=0)
124
+ assert_array_almost_equal(xp.real(a)[1:, 1:], expected[:-1, :-1], decimal=dec)
125
+ assert_array_almost_equal(xp.imag(a), xp.zeros(shape), decimal=dec)
126
+
127
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
128
+ @pytest.mark.parametrize('dtype, dec', [("float32", 5), ("float64", 14)])
129
+ @make_xp_test_case(ndimage.fourier_ellipsoid)
130
+ def test_fourier_ellipsoid_real01(self, shape, dtype, dec, xp):
131
+ fft = getattr(xp, 'fft')
132
+
133
+ a = np.zeros(shape, dtype=dtype)
134
+ a[0, 0] = 1.0
135
+ a = xp.asarray(a)
136
+
137
+ a = fft.rfft(a, n=shape[0], axis=0)
138
+ a = fft.fft(a, n=shape[1], axis=1)
139
+ a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], shape[0], 0)
140
+ a = fft.ifft(a, n=shape[1], axis=1)
141
+ a = fft.irfft(a, n=shape[0], axis=0)
142
+ assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec,
143
+ check_0d=False)
144
+
145
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
146
+ @pytest.mark.parametrize('dtype, dec', [("complex64", 5), ("complex128", 14)])
147
+ @make_xp_test_case(ndimage.fourier_ellipsoid)
148
+ def test_fourier_ellipsoid_complex01(self, shape, dtype, dec, xp):
149
+ fft = getattr(xp, 'fft')
150
+
151
+ a = np.zeros(shape, dtype=dtype)
152
+ a[0, 0] = 1.0
153
+ a = xp.asarray(a)
154
+
155
+ a = fft.fft(a, n=shape[0], axis=0)
156
+ a = fft.fft(a, n=shape[1], axis=1)
157
+ a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], -1, 0)
158
+ a = fft.ifft(a, n=shape[1], axis=1)
159
+ a = fft.ifft(a, n=shape[0], axis=0)
160
+ assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
161
+ check_0d=False)
162
+
163
+ @make_xp_test_case(ndimage.fourier_ellipsoid)
164
+ def test_fourier_ellipsoid_unimplemented_ndim(self, xp):
165
+ # arrays with ndim > 3 raise NotImplementedError
166
+ x = xp.ones((4, 6, 8, 10), dtype=xp.complex128)
167
+ with pytest.raises(NotImplementedError):
168
+ ndimage.fourier_ellipsoid(x, 3)
169
+
170
+ @make_xp_test_case(ndimage.fourier_ellipsoid)
171
+ def test_fourier_ellipsoid_1d_complex(self, xp):
172
+ # expected result of 1d ellipsoid is the same as for fourier_uniform
173
+ for shape in [(32, ), (31, )]:
174
+ for type_, dec in zip([xp.complex64, xp.complex128], [5, 14]):
175
+ x = xp.ones(shape, dtype=type_)
176
+ a = ndimage.fourier_ellipsoid(x, 5, -1, 0)
177
+ b = ndimage.fourier_uniform(x, 5, -1, 0)
178
+ assert_array_almost_equal(a, b, decimal=dec)
179
+
180
+ @pytest.mark.parametrize('shape', [(0, ), (0, 10), (10, 0)])
181
+ @pytest.mark.parametrize('dtype', ["float32", "float64",
182
+ "complex64", "complex128"])
183
+ @pytest.mark.parametrize('test_func',
184
+ [make_xp_pytest_param(ndimage.fourier_ellipsoid),
185
+ make_xp_pytest_param(ndimage.fourier_gaussian),
186
+ make_xp_pytest_param(ndimage.fourier_uniform)])
187
+ def test_fourier_zero_length_dims(self, shape, dtype, test_func, xp):
188
+ if (
189
+ is_cupy(xp)
190
+ and test_func.__name__ == "fourier_ellipsoid"
191
+ and math.prod(shape) == 0
192
+ ):
193
+ pytest.xfail("CuPy's fourier_ellipsoid does not accept size==0 arrays")
194
+ dtype = getattr(xp, dtype)
195
+ a = xp.ones(shape, dtype=dtype)
196
+ b = test_func(a, 3)
197
+ xp_assert_equal(a, b)
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_interpolation.py ADDED
@@ -0,0 +1,1499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import warnings
3
+
4
+ import numpy as np
5
+ from scipy._lib._array_api import (
6
+ _asarray, assert_array_almost_equal,
7
+ is_jax, np_compat,
8
+ xp_assert_equal, xp_assert_close,
9
+ make_xp_test_case,
10
+ )
11
+
12
+ import pytest
13
+ from pytest import raises as assert_raises
14
+ import scipy.ndimage as ndimage
15
+
16
+ from . import types
17
+
18
+ skip_xp_backends = pytest.mark.skip_xp_backends
19
+ xfail_xp_backends = pytest.mark.xfail_xp_backends
20
+ # lazy_xp_modules = [ndimage]
21
+
22
+
23
+ eps = 1e-12
24
+
25
+ ndimage_to_numpy_mode = {
26
+ 'mirror': 'reflect',
27
+ 'reflect': 'symmetric',
28
+ 'grid-mirror': 'symmetric',
29
+ 'grid-wrap': 'wrap',
30
+ 'nearest': 'edge',
31
+ 'grid-constant': 'constant',
32
+ }
33
+
34
+
35
+ class TestBoundaries:
36
+
37
+ @make_xp_test_case(ndimage.geometric_transform)
38
+ @pytest.mark.parametrize(
39
+ 'mode, expected_value',
40
+ [('nearest', [1.5, 2.5, 3.5, 4, 4, 4, 4]),
41
+ ('wrap', [1.5, 2.5, 3.5, 1.5, 2.5, 3.5, 1.5]),
42
+ ('grid-wrap', [1.5, 2.5, 3.5, 2.5, 1.5, 2.5, 3.5]),
43
+ ('mirror', [1.5, 2.5, 3.5, 3.5, 2.5, 1.5, 1.5]),
44
+ ('reflect', [1.5, 2.5, 3.5, 4, 3.5, 2.5, 1.5]),
45
+ ('constant', [1.5, 2.5, 3.5, -1, -1, -1, -1]),
46
+ ('grid-constant', [1.5, 2.5, 3.5, 1.5, -1, -1, -1])]
47
+ )
48
+ def test_boundaries(self, mode, expected_value, xp):
49
+ def shift(x):
50
+ return (x[0] + 0.5,)
51
+
52
+ data = xp.asarray([1, 2, 3, 4.])
53
+ xp_assert_equal(
54
+ ndimage.geometric_transform(data, shift, cval=-1, mode=mode,
55
+ output_shape=(7,), order=1),
56
+ xp.asarray(expected_value))
57
+
58
+ @make_xp_test_case(ndimage.geometric_transform)
59
+ @pytest.mark.parametrize(
60
+ 'mode, expected_value',
61
+ [('nearest', [1, 1, 2, 3]),
62
+ ('wrap', [3, 1, 2, 3]),
63
+ ('grid-wrap', [4, 1, 2, 3]),
64
+ ('mirror', [2, 1, 2, 3]),
65
+ ('reflect', [1, 1, 2, 3]),
66
+ ('constant', [-1, 1, 2, 3]),
67
+ ('grid-constant', [-1, 1, 2, 3])]
68
+ )
69
+ def test_boundaries2(self, mode, expected_value, xp):
70
+ def shift(x):
71
+ return (x[0] - 0.9,)
72
+
73
+ data = xp.asarray([1, 2, 3, 4])
74
+ xp_assert_equal(
75
+ ndimage.geometric_transform(data, shift, cval=-1, mode=mode,
76
+ output_shape=(4,)),
77
+ xp.asarray(expected_value))
78
+
79
+ @make_xp_test_case(ndimage.map_coordinates)
80
+ @pytest.mark.parametrize('mode', ['mirror', 'reflect', 'grid-mirror',
81
+ 'grid-wrap', 'grid-constant',
82
+ 'nearest'])
83
+ @pytest.mark.parametrize('order', range(6))
84
+ def test_boundary_spline_accuracy(self, mode, order, xp):
85
+ """Tests based on examples from gh-2640"""
86
+ if (is_jax(xp) and
87
+ (mode not in ['mirror', 'reflect', 'constant', 'wrap', 'nearest']
88
+ or order > 1)
89
+ ):
90
+ pytest.xfail("Jax does not support grid- modes or order > 1")
91
+
92
+ np_data = np.arange(-6, 7, dtype=np.float64)
93
+ data = xp.asarray(np_data)
94
+ x = xp.asarray(np.linspace(-8, 15, num=1000))
95
+ y = ndimage.map_coordinates(data, x[xp.newaxis, ...], order=order, mode=mode)
96
+
97
+ # compute expected value using explicit padding via np.pad
98
+ npad = 32
99
+ pad_mode = ndimage_to_numpy_mode.get(mode)
100
+ padded = xp.asarray(np.pad(np_data, npad, mode=pad_mode))
101
+ coords = xp.asarray(npad + x)[xp.newaxis, ...]
102
+ expected = ndimage.map_coordinates(padded, coords, order=order, mode=mode)
103
+
104
+ atol = 1e-5 if mode == 'grid-constant' else 1e-12
105
+ xp_assert_close(y, expected, rtol=1e-7, atol=atol)
106
+
107
+
108
+ @make_xp_test_case(ndimage.spline_filter)
109
+ @pytest.mark.parametrize('order', range(2, 6))
110
+ @pytest.mark.parametrize('dtype', types)
111
+ class TestSpline:
112
+
113
+ def test_spline01(self, dtype, order, xp):
114
+ dtype = getattr(xp, dtype)
115
+ data = xp.ones([], dtype=dtype)
116
+ out = ndimage.spline_filter(data, order=order)
117
+ assert out == xp.asarray(1, dtype=out.dtype)
118
+
119
+ def test_spline02(self, dtype, order, xp):
120
+ dtype = getattr(xp, dtype)
121
+ data = xp.asarray([1], dtype=dtype)
122
+ out = ndimage.spline_filter(data, order=order)
123
+ assert_array_almost_equal(out, xp.asarray([1]))
124
+
125
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
126
+ reason='output=dtype is numpy-specific')
127
+ def test_spline03(self, dtype, order, xp):
128
+ dtype = getattr(xp, dtype)
129
+ data = xp.ones([], dtype=dtype)
130
+ out = ndimage.spline_filter(data, order, output=dtype)
131
+ assert out == xp.asarray(1, dtype=out.dtype)
132
+
133
+ def test_spline04(self, dtype, order, xp):
134
+ dtype = getattr(xp, dtype)
135
+ data = xp.ones([4], dtype=dtype)
136
+ out = ndimage.spline_filter(data, order)
137
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1]))
138
+
139
+ def test_spline05(self, dtype, order, xp):
140
+ dtype = getattr(xp, dtype)
141
+ data = xp.ones([4, 4], dtype=dtype)
142
+ out = ndimage.spline_filter(data, order=order)
143
+ expected = xp.asarray([[1, 1, 1, 1],
144
+ [1, 1, 1, 1],
145
+ [1, 1, 1, 1],
146
+ [1, 1, 1, 1]])
147
+ assert_array_almost_equal(out, expected)
148
+
149
+
150
+ @make_xp_test_case(ndimage.geometric_transform)
151
+ @pytest.mark.parametrize('order', range(0, 6))
152
+ class TestGeometricTransform:
153
+
154
+ def test_geometric_transform01(self, order, xp):
155
+ data = xp.asarray([1])
156
+
157
+ def mapping(x):
158
+ return x
159
+
160
+ out = ndimage.geometric_transform(data, mapping, data.shape,
161
+ order=order)
162
+ assert_array_almost_equal(out, xp.asarray([1], dtype=out.dtype))
163
+
164
+ def test_geometric_transform02(self, order, xp):
165
+ data = xp.ones([4])
166
+
167
+ def mapping(x):
168
+ return x
169
+
170
+ out = ndimage.geometric_transform(data, mapping, data.shape,
171
+ order=order)
172
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1], dtype=out.dtype))
173
+
174
+ def test_geometric_transform03(self, order, xp):
175
+ data = xp.ones([4])
176
+
177
+ def mapping(x):
178
+ return (x[0] - 1,)
179
+
180
+ out = ndimage.geometric_transform(data, mapping, data.shape,
181
+ order=order)
182
+ assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1], dtype=out.dtype))
183
+
184
+ def test_geometric_transform04(self, order, xp):
185
+ data = xp.asarray([4, 1, 3, 2])
186
+
187
+ def mapping(x):
188
+ return (x[0] - 1,)
189
+
190
+ out = ndimage.geometric_transform(data, mapping, data.shape,
191
+ order=order)
192
+ assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3], dtype=out.dtype))
193
+
194
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
195
+ def test_geometric_transform05(self, order, dtype, xp):
196
+ dtype = getattr(xp, dtype)
197
+ data = xp.asarray([[1, 1, 1, 1],
198
+ [1, 1, 1, 1],
199
+ [1, 1, 1, 1]], dtype=dtype)
200
+ expected = xp.asarray([[0, 1, 1, 1],
201
+ [0, 1, 1, 1],
202
+ [0, 1, 1, 1]], dtype=dtype)
203
+
204
+ if xp.isdtype(data.dtype, 'complex floating'):
205
+ data -= 1j * data
206
+ expected -= 1j * expected
207
+
208
+ def mapping(x):
209
+ return (x[0], x[1] - 1)
210
+
211
+ out = ndimage.geometric_transform(data, mapping, data.shape,
212
+ order=order)
213
+ assert_array_almost_equal(out, expected)
214
+
215
+ def test_geometric_transform06(self, order, xp):
216
+ data = xp.asarray([[4, 1, 3, 2],
217
+ [7, 6, 8, 5],
218
+ [3, 5, 3, 6]])
219
+
220
+ def mapping(x):
221
+ return (x[0], x[1] - 1)
222
+
223
+ out = ndimage.geometric_transform(data, mapping, data.shape,
224
+ order=order)
225
+ expected = xp.asarray([[0, 4, 1, 3],
226
+ [0, 7, 6, 8],
227
+ [0, 3, 5, 3]], dtype=out.dtype)
228
+ assert_array_almost_equal(out, expected)
229
+
230
+ def test_geometric_transform07(self, order, xp):
231
+ data = xp.asarray([[4, 1, 3, 2],
232
+ [7, 6, 8, 5],
233
+ [3, 5, 3, 6]])
234
+
235
+ def mapping(x):
236
+ return (x[0] - 1, x[1])
237
+
238
+ out = ndimage.geometric_transform(data, mapping, data.shape,
239
+ order=order)
240
+ expected = xp.asarray([[0, 0, 0, 0],
241
+ [4, 1, 3, 2],
242
+ [7, 6, 8, 5]], dtype=out.dtype)
243
+ assert_array_almost_equal(out, expected)
244
+
245
+ def test_geometric_transform08(self, order, xp):
246
+ data = xp.asarray([[4, 1, 3, 2],
247
+ [7, 6, 8, 5],
248
+ [3, 5, 3, 6]])
249
+
250
+ def mapping(x):
251
+ return (x[0] - 1, x[1] - 1)
252
+
253
+ out = ndimage.geometric_transform(data, mapping, data.shape,
254
+ order=order)
255
+ expected = xp.asarray([[0, 0, 0, 0],
256
+ [0, 4, 1, 3],
257
+ [0, 7, 6, 8]], dtype=out.dtype)
258
+ assert_array_almost_equal(out, expected)
259
+
260
+ def test_geometric_transform10(self, order, xp):
261
+ data = xp.asarray([[4, 1, 3, 2],
262
+ [7, 6, 8, 5],
263
+ [3, 5, 3, 6]])
264
+
265
+ def mapping(x):
266
+ return (x[0] - 1, x[1] - 1)
267
+
268
+ if (order > 1):
269
+ filtered = ndimage.spline_filter(data, order=order)
270
+ else:
271
+ filtered = data
272
+ out = ndimage.geometric_transform(filtered, mapping, data.shape,
273
+ order=order, prefilter=False)
274
+ expected = xp.asarray([[0, 0, 0, 0],
275
+ [0, 4, 1, 3],
276
+ [0, 7, 6, 8]], dtype=out.dtype)
277
+ assert_array_almost_equal(out, expected)
278
+
279
+ def test_geometric_transform13(self, order, xp):
280
+ data = xp.ones([2], dtype=xp.float64)
281
+
282
+ def mapping(x):
283
+ return (x[0] // 2,)
284
+
285
+ out = ndimage.geometric_transform(data, mapping, [4], order=order)
286
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1], dtype=out.dtype))
287
+
288
+ def test_geometric_transform14(self, order, xp):
289
+ data = xp.asarray([1, 5, 2, 6, 3, 7, 4, 4])
290
+
291
+ def mapping(x):
292
+ return (2 * x[0],)
293
+
294
+ out = ndimage.geometric_transform(data, mapping, [4], order=order)
295
+ assert_array_almost_equal(out, xp.asarray([1, 2, 3, 4], dtype=out.dtype))
296
+
297
+ def test_geometric_transform15(self, order, xp):
298
+ data = xp.asarray([1, 2, 3, 4])
299
+
300
+ def mapping(x):
301
+ return (x[0] / 2,)
302
+
303
+ out = ndimage.geometric_transform(data, mapping, [8], order=order)
304
+ assert_array_almost_equal(out[::2], xp.asarray([1, 2, 3, 4]))
305
+
306
+ def test_geometric_transform16(self, order, xp):
307
+ data = [[1, 2, 3, 4],
308
+ [5, 6, 7, 8],
309
+ [9.0, 10, 11, 12]]
310
+ data = xp.asarray(data)
311
+
312
+ def mapping(x):
313
+ return (x[0], x[1] * 2)
314
+
315
+ out = ndimage.geometric_transform(data, mapping, (3, 2),
316
+ order=order)
317
+ assert_array_almost_equal(out, xp.asarray([[1, 3], [5, 7], [9, 11]]))
318
+
319
+ def test_geometric_transform17(self, order, xp):
320
+ data = [[1, 2, 3, 4],
321
+ [5, 6, 7, 8],
322
+ [9, 10, 11, 12]]
323
+ data = xp.asarray(data)
324
+
325
+ def mapping(x):
326
+ return (x[0] * 2, x[1])
327
+
328
+ out = ndimage.geometric_transform(data, mapping, (1, 4),
329
+ order=order)
330
+ assert_array_almost_equal(out, xp.asarray([[1, 2, 3, 4]]))
331
+
332
+ def test_geometric_transform18(self, order, xp):
333
+ data = [[1, 2, 3, 4],
334
+ [5, 6, 7, 8],
335
+ [9, 10, 11, 12]]
336
+ data = xp.asarray(data)
337
+
338
+ def mapping(x):
339
+ return (x[0] * 2, x[1] * 2)
340
+
341
+ out = ndimage.geometric_transform(data, mapping, (1, 2),
342
+ order=order)
343
+ assert_array_almost_equal(out, xp.asarray([[1, 3]]))
344
+
345
+ def test_geometric_transform19(self, order, xp):
346
+ data = [[1, 2, 3, 4],
347
+ [5, 6, 7, 8],
348
+ [9, 10, 11, 12]]
349
+ data = xp.asarray(data)
350
+
351
+ def mapping(x):
352
+ return (x[0], x[1] / 2)
353
+
354
+ out = ndimage.geometric_transform(data, mapping, (3, 8),
355
+ order=order)
356
+ assert_array_almost_equal(out[..., ::2], data)
357
+
358
+ def test_geometric_transform20(self, order, xp):
359
+ data = [[1, 2, 3, 4],
360
+ [5, 6, 7, 8],
361
+ [9, 10, 11, 12]]
362
+ data = xp.asarray(data)
363
+
364
+ def mapping(x):
365
+ return (x[0] / 2, x[1])
366
+
367
+ out = ndimage.geometric_transform(data, mapping, (6, 4),
368
+ order=order)
369
+ assert_array_almost_equal(out[::2, ...], data)
370
+
371
+ def test_geometric_transform21(self, order, xp):
372
+ data = [[1, 2, 3, 4],
373
+ [5, 6, 7, 8],
374
+ [9, 10, 11, 12]]
375
+ data = xp.asarray(data)
376
+
377
+ def mapping(x):
378
+ return (x[0] / 2, x[1] / 2)
379
+
380
+ out = ndimage.geometric_transform(data, mapping, (6, 8),
381
+ order=order)
382
+ assert_array_almost_equal(out[::2, ::2], data)
383
+
384
+ def test_geometric_transform22(self, order, xp):
385
+ data = [[1, 2, 3, 4],
386
+ [5, 6, 7, 8],
387
+ [9, 10, 11, 12]]
388
+ data = xp.asarray(data, dtype=xp.float64)
389
+
390
+ def mapping1(x):
391
+ return (x[0] / 2, x[1] / 2)
392
+
393
+ def mapping2(x):
394
+ return (x[0] * 2, x[1] * 2)
395
+
396
+ out = ndimage.geometric_transform(data, mapping1,
397
+ (6, 8), order=order)
398
+ out = ndimage.geometric_transform(out, mapping2,
399
+ (3, 4), order=order)
400
+ assert_array_almost_equal(out, data)
401
+
402
+ def test_geometric_transform23(self, order, xp):
403
+ data = [[1, 2, 3, 4],
404
+ [5, 6, 7, 8],
405
+ [9, 10, 11, 12]]
406
+ data = xp.asarray(data)
407
+
408
+ def mapping(x):
409
+ return (1, x[0] * 2)
410
+
411
+ out = ndimage.geometric_transform(data, mapping, (2,), order=order)
412
+ assert_array_almost_equal(out, xp.asarray([5, 7]))
413
+
414
+ def test_geometric_transform24(self, order, xp):
415
+ data = [[1, 2, 3, 4],
416
+ [5, 6, 7, 8],
417
+ [9, 10, 11, 12]]
418
+ data = xp.asarray(data)
419
+
420
+ def mapping(x, a, b):
421
+ return (a, x[0] * b)
422
+
423
+ out = ndimage.geometric_transform(
424
+ data, mapping, (2,), order=order, extra_arguments=(1,),
425
+ extra_keywords={'b': 2})
426
+ assert_array_almost_equal(out, xp.asarray([5, 7]))
427
+
428
+
429
+ @make_xp_test_case(ndimage.geometric_transform)
430
+ class TestGeometricTransformExtra:
431
+
432
+ def test_geometric_transform_grid_constant_order1(self, xp):
433
+
434
+ # verify interpolation outside the original bounds
435
+ x = xp.asarray([[1, 2, 3],
436
+ [4, 5, 6]], dtype=xp.float64)
437
+
438
+ def mapping(x):
439
+ return (x[0] - 0.5), (x[1] - 0.5)
440
+
441
+ expected_result = xp.asarray([[0.25, 0.75, 1.25],
442
+ [1.25, 3.00, 4.00]])
443
+ assert_array_almost_equal(
444
+ ndimage.geometric_transform(x, mapping, mode='grid-constant',
445
+ order=1),
446
+ expected_result,
447
+ )
448
+
449
+ @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest',
450
+ 'mirror', 'reflect'])
451
+ @pytest.mark.parametrize('order', range(6))
452
+ def test_geometric_transform_vs_padded(self, order, mode, xp):
453
+
454
+ def mapping(x):
455
+ return (x[0] - 0.4), (x[1] + 2.3)
456
+
457
+ # Manually pad and then extract center after the transform to get the
458
+ # expected result.
459
+ x = np.arange(144, dtype=float).reshape(12, 12)
460
+ npad = 24
461
+ pad_mode = ndimage_to_numpy_mode.get(mode)
462
+ x_padded = np.pad(x, npad, mode=pad_mode)
463
+
464
+ x = xp.asarray(x)
465
+ x_padded = xp.asarray(x_padded)
466
+
467
+ center_slice = tuple([slice(npad, -npad)] * x.ndim)
468
+ expected_result = ndimage.geometric_transform(
469
+ x_padded, mapping, mode=mode, order=order)[center_slice]
470
+
471
+ xp_assert_close(
472
+ ndimage.geometric_transform(x, mapping, mode=mode,
473
+ order=order),
474
+ expected_result,
475
+ rtol=1e-7,
476
+ )
477
+
478
+ @skip_xp_backends(np_only=True, reason='endianness is numpy-specific')
479
+ def test_geometric_transform_endianness_with_output_parameter(self, xp):
480
+ # geometric transform given output ndarray or dtype with
481
+ # non-native endianness. see issue #4127
482
+ data = np.asarray([1])
483
+
484
+ def mapping(x):
485
+ return x
486
+
487
+ for out in [data.dtype, data.dtype.newbyteorder(),
488
+ np.empty_like(data),
489
+ np.empty_like(data).astype(data.dtype.newbyteorder())]:
490
+ returned = ndimage.geometric_transform(data, mapping, data.shape,
491
+ output=out)
492
+ result = out if returned is None else returned
493
+ assert_array_almost_equal(result, [1])
494
+
495
+ @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
496
+ def test_geometric_transform_with_string_output(self, xp):
497
+ data = xp.asarray([1])
498
+
499
+ def mapping(x):
500
+ return x
501
+
502
+ out = ndimage.geometric_transform(data, mapping, output='f')
503
+ assert out.dtype is np.dtype('f')
504
+ assert_array_almost_equal(out, [1])
505
+
506
+
507
+ @make_xp_test_case(ndimage.map_coordinates)
508
+ class TestMapCoordinates:
509
+
510
+ @pytest.mark.parametrize('order', range(0, 6))
511
+ @pytest.mark.parametrize('dtype', [np.float64, np.complex128])
512
+ def test_map_coordinates01(self, order, dtype, xp):
513
+ if is_jax(xp) and order > 1:
514
+ pytest.xfail("jax map_coordinates requires order <= 1")
515
+
516
+ data = xp.asarray([[4, 1, 3, 2],
517
+ [7, 6, 8, 5],
518
+ [3, 5, 3, 6]])
519
+ expected = xp.asarray([[0, 0, 0, 0],
520
+ [0, 4, 1, 3],
521
+ [0, 7, 6, 8]])
522
+ if xp.isdtype(data.dtype, 'complex floating'):
523
+ data = data - 1j * data
524
+ expected = expected - 1j * expected
525
+
526
+ idx = np.indices(data.shape)
527
+ idx -= 1
528
+ idx = xp.asarray(idx)
529
+
530
+ out = ndimage.map_coordinates(data, idx, order=order)
531
+ assert_array_almost_equal(out, expected)
532
+
533
+ @pytest.mark.parametrize('order', range(0, 6))
534
+ def test_map_coordinates02(self, order, xp):
535
+ if is_jax(xp):
536
+ if order > 1:
537
+ pytest.xfail("jax map_coordinates requires order <= 1")
538
+ if order == 1:
539
+ pytest.xfail("output differs. jax bug?")
540
+
541
+ data = xp.asarray([[4, 1, 3, 2],
542
+ [7, 6, 8, 5],
543
+ [3, 5, 3, 6]])
544
+ idx = np.indices(data.shape, np.float64)
545
+ idx -= 0.5
546
+ idx = xp.asarray(idx)
547
+
548
+ out1 = ndimage.shift(data, 0.5, order=order)
549
+ out2 = ndimage.map_coordinates(data, idx, order=order)
550
+ assert_array_almost_equal(out1, out2)
551
+
552
+ @skip_xp_backends("jax.numpy", reason="`order` is required in jax")
553
+ def test_map_coordinates03(self, xp):
554
+ data = _asarray([[4, 1, 3, 2],
555
+ [7, 6, 8, 5],
556
+ [3, 5, 3, 6]], order='F', xp=xp)
557
+ idx = np.indices(data.shape) - 1
558
+ idx = xp.asarray(idx)
559
+ out = ndimage.map_coordinates(data, idx)
560
+ expected = xp.asarray([[0, 0, 0, 0],
561
+ [0, 4, 1, 3],
562
+ [0, 7, 6, 8]])
563
+ assert_array_almost_equal(out, expected)
564
+ assert_array_almost_equal(out, ndimage.shift(data, (1, 1)))
565
+
566
+ idx = np.indices(data[::2, ...].shape) - 1
567
+ idx = xp.asarray(idx)
568
+ out = ndimage.map_coordinates(data[::2, ...], idx)
569
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
570
+ [0, 4, 1, 3]]))
571
+ assert_array_almost_equal(out, ndimage.shift(data[::2, ...], (1, 1)))
572
+
573
+ idx = np.indices(data[:, ::2].shape) - 1
574
+ idx = xp.asarray(idx)
575
+ out = ndimage.map_coordinates(data[:, ::2], idx)
576
+ assert_array_almost_equal(out, xp.asarray([[0, 0], [0, 4], [0, 7]]))
577
+ assert_array_almost_equal(out, ndimage.shift(data[:, ::2], (1, 1)))
578
+
579
+ @skip_xp_backends(np_only=True)
580
+ def test_map_coordinates_endianness_with_output_parameter(self, xp):
581
+ # output parameter given as array or dtype with either endianness
582
+ # see issue #4127
583
+ # NB: NumPy-only
584
+
585
+ data = np.asarray([[1, 2], [7, 6]])
586
+ expected = np.asarray([[0, 0], [0, 1]])
587
+ idx = np.indices(data.shape)
588
+ idx -= 1
589
+ for out in [
590
+ data.dtype,
591
+ data.dtype.newbyteorder(),
592
+ np.empty_like(expected),
593
+ np.empty_like(expected).astype(expected.dtype.newbyteorder())
594
+ ]:
595
+ returned = ndimage.map_coordinates(data, idx, output=out)
596
+ result = out if returned is None else returned
597
+ assert_array_almost_equal(result, expected)
598
+
599
+ @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
600
+ def test_map_coordinates_with_string_output(self, xp):
601
+ data = xp.asarray([[1]])
602
+ idx = np.indices(data.shape)
603
+ idx = xp.asarray(idx)
604
+ out = ndimage.map_coordinates(data, idx, output='f')
605
+ assert out.dtype is np.dtype('f')
606
+ assert_array_almost_equal(out, xp.asarray([[1]]))
607
+
608
+ @pytest.mark.skip_xp_backends(cpu_only=True)
609
+ @pytest.mark.skipif('win32' in sys.platform or np.intp(0).itemsize < 8,
610
+ reason='do not run on 32 bit or windows '
611
+ '(no sparse memory)')
612
+ def test_map_coordinates_large_data(self, xp):
613
+ # check crash on large data
614
+ try:
615
+ n = 30000
616
+ # a = xp.reshape(xp.empty(n**2, dtype=xp.float32), (n, n))
617
+ a = np.empty(n**2, dtype=np.float32).reshape(n, n)
618
+ # fill the part we might read
619
+ a[n - 3:, n - 3:] = 0
620
+ ndimage.map_coordinates(
621
+ xp.asarray(a), xp.asarray([[n - 1.5], [n - 1.5]]), order=1
622
+ )
623
+ except MemoryError as e:
624
+ raise pytest.skip('Not enough memory available') from e
625
+
626
+
627
+ @make_xp_test_case(ndimage.affine_transform)
628
+ class TestAffineTransform:
629
+
630
+ @pytest.mark.parametrize('order', range(0, 6))
631
+ def test_affine_transform01(self, order, xp):
632
+ data = xp.asarray([1])
633
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), order=order)
634
+ assert_array_almost_equal(out, xp.asarray([1]))
635
+
636
+ @pytest.mark.parametrize('order', range(0, 6))
637
+ def test_affine_transform02(self, order, xp):
638
+ data = xp.ones([4])
639
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), order=order)
640
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1]))
641
+
642
+ @pytest.mark.parametrize('order', range(0, 6))
643
+ def test_affine_transform03(self, order, xp):
644
+ data = xp.ones([4])
645
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), -1, order=order)
646
+ assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1]))
647
+
648
+ @pytest.mark.parametrize('order', range(0, 6))
649
+ def test_affine_transform04(self, order, xp):
650
+ data = xp.asarray([4, 1, 3, 2])
651
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), -1, order=order)
652
+ assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3]))
653
+
654
+ @pytest.mark.parametrize('order', range(0, 6))
655
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
656
+ def test_affine_transform05(self, order, dtype, xp):
657
+ dtype = getattr(xp, dtype)
658
+ data = xp.asarray([[1, 1, 1, 1],
659
+ [1, 1, 1, 1],
660
+ [1, 1, 1, 1]], dtype=dtype)
661
+ expected = xp.asarray([[0, 1, 1, 1],
662
+ [0, 1, 1, 1],
663
+ [0, 1, 1, 1]], dtype=dtype)
664
+ if xp.isdtype(data.dtype, 'complex floating'):
665
+ data -= 1j * data
666
+ expected -= 1j * expected
667
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
668
+ [0, -1], order=order)
669
+ assert_array_almost_equal(out, expected)
670
+
671
+ @pytest.mark.parametrize('order', range(0, 6))
672
+ def test_affine_transform06(self, order, xp):
673
+ data = xp.asarray([[4, 1, 3, 2],
674
+ [7, 6, 8, 5],
675
+ [3, 5, 3, 6]])
676
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
677
+ [0, -1], order=order)
678
+ assert_array_almost_equal(out, xp.asarray([[0, 4, 1, 3],
679
+ [0, 7, 6, 8],
680
+ [0, 3, 5, 3]]))
681
+
682
+ @pytest.mark.parametrize('order', range(0, 6))
683
+ def test_affine_transform07(self, order, xp):
684
+ data = xp.asarray([[4, 1, 3, 2],
685
+ [7, 6, 8, 5],
686
+ [3, 5, 3, 6]])
687
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
688
+ [-1, 0], order=order)
689
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
690
+ [4, 1, 3, 2],
691
+ [7, 6, 8, 5]]))
692
+
693
+ @pytest.mark.parametrize('order', range(0, 6))
694
+ def test_affine_transform08(self, order, xp):
695
+ data = xp.asarray([[4, 1, 3, 2],
696
+ [7, 6, 8, 5],
697
+ [3, 5, 3, 6]])
698
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
699
+ [-1, -1], order=order)
700
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
701
+ [0, 4, 1, 3],
702
+ [0, 7, 6, 8]]))
703
+
704
+ @pytest.mark.parametrize('order', range(0, 6))
705
+ def test_affine_transform09(self, order, xp):
706
+ data = xp.asarray([[4, 1, 3, 2],
707
+ [7, 6, 8, 5],
708
+ [3, 5, 3, 6]])
709
+ if (order > 1):
710
+ filtered = ndimage.spline_filter(data, order=order)
711
+ else:
712
+ filtered = data
713
+ out = ndimage.affine_transform(filtered, xp.asarray([[1, 0], [0, 1]]),
714
+ [-1, -1], order=order,
715
+ prefilter=False)
716
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
717
+ [0, 4, 1, 3],
718
+ [0, 7, 6, 8]]))
719
+
720
+ @pytest.mark.parametrize('order', range(0, 6))
721
+ def test_affine_transform10(self, order, xp):
722
+ data = xp.ones([2], dtype=xp.float64)
723
+ out = ndimage.affine_transform(data, xp.asarray([[0.5]]), output_shape=(4,),
724
+ order=order)
725
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0]))
726
+
727
+ @pytest.mark.parametrize('order', range(0, 6))
728
+ def test_affine_transform11(self, order, xp):
729
+ data = xp.asarray([1, 5, 2, 6, 3, 7, 4, 4])
730
+ out = ndimage.affine_transform(data, xp.asarray([[2]]), 0, (4,), order=order)
731
+ assert_array_almost_equal(out, xp.asarray([1, 2, 3, 4]))
732
+
733
+ @pytest.mark.parametrize('order', range(0, 6))
734
+ def test_affine_transform12(self, order, xp):
735
+ data = xp.asarray([1, 2, 3, 4])
736
+ out = ndimage.affine_transform(data, xp.asarray([[0.5]]), 0, (8,), order=order)
737
+ assert_array_almost_equal(out[::2], xp.asarray([1, 2, 3, 4]))
738
+
739
+ @pytest.mark.parametrize('order', range(0, 6))
740
+ def test_affine_transform13(self, order, xp):
741
+ data = [[1, 2, 3, 4],
742
+ [5, 6, 7, 8],
743
+ [9.0, 10, 11, 12]]
744
+ data = xp.asarray(data)
745
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 2]]), 0, (3, 2),
746
+ order=order)
747
+ assert_array_almost_equal(out, xp.asarray([[1, 3], [5, 7], [9, 11]]))
748
+
749
+ @pytest.mark.parametrize('order', range(0, 6))
750
+ def test_affine_transform14(self, order, xp):
751
+ data = [[1, 2, 3, 4],
752
+ [5, 6, 7, 8],
753
+ [9, 10, 11, 12]]
754
+ data = xp.asarray(data)
755
+ out = ndimage.affine_transform(data, xp.asarray([[2, 0], [0, 1]]), 0, (1, 4),
756
+ order=order)
757
+ assert_array_almost_equal(out, xp.asarray([[1, 2, 3, 4]]))
758
+
759
+ @pytest.mark.parametrize('order', range(0, 6))
760
+ def test_affine_transform15(self, order, xp):
761
+ data = [[1, 2, 3, 4],
762
+ [5, 6, 7, 8],
763
+ [9, 10, 11, 12]]
764
+ data = xp.asarray(data)
765
+ out = ndimage.affine_transform(data, xp.asarray([[2, 0], [0, 2]]), 0, (1, 2),
766
+ order=order)
767
+ assert_array_almost_equal(out, xp.asarray([[1, 3]]))
768
+
769
+ @pytest.mark.parametrize('order', range(0, 6))
770
+ def test_affine_transform16(self, order, xp):
771
+ data = [[1, 2, 3, 4],
772
+ [5, 6, 7, 8],
773
+ [9, 10, 11, 12]]
774
+ data = xp.asarray(data)
775
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0.0], [0, 0.5]]), 0,
776
+ (3, 8), order=order)
777
+ assert_array_almost_equal(out[..., ::2], data)
778
+
779
+ @pytest.mark.parametrize('order', range(0, 6))
780
+ def test_affine_transform17(self, order, xp):
781
+ data = [[1, 2, 3, 4],
782
+ [5, 6, 7, 8],
783
+ [9, 10, 11, 12]]
784
+ data = xp.asarray(data)
785
+ out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 1]]), 0,
786
+ (6, 4), order=order)
787
+ assert_array_almost_equal(out[::2, ...], data)
788
+
789
+ @pytest.mark.parametrize('order', range(0, 6))
790
+ def test_affine_transform18(self, order, xp):
791
+ data = xp.asarray([[1, 2, 3, 4],
792
+ [5, 6, 7, 8],
793
+ [9, 10, 11, 12]])
794
+ out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 0.5]]), 0,
795
+ (6, 8), order=order)
796
+ assert_array_almost_equal(out[::2, ::2], data)
797
+
798
+ @pytest.mark.parametrize('order', range(0, 6))
799
+ def test_affine_transform19(self, order, xp):
800
+ data = xp.asarray([[1, 2, 3, 4],
801
+ [5, 6, 7, 8],
802
+ [9, 10, 11, 12]], dtype=xp.float64)
803
+ out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 0.5]]), 0,
804
+ (6, 8), order=order)
805
+ out = ndimage.affine_transform(out, xp.asarray([[2.0, 0], [0, 2.0]]), 0,
806
+ (3, 4), order=order)
807
+ assert_array_almost_equal(out, data)
808
+
809
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8394")
810
+ @pytest.mark.parametrize('order', range(0, 6))
811
+ def test_affine_transform20(self, order, xp):
812
+ data = [[1, 2, 3, 4],
813
+ [5, 6, 7, 8],
814
+ [9, 10, 11, 12]]
815
+ data = xp.asarray(data)
816
+ out = ndimage.affine_transform(data, xp.asarray([[0], [2]]), 0, (2,),
817
+ order=order)
818
+ assert_array_almost_equal(out, xp.asarray([1, 3]))
819
+
820
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8394")
821
+ @pytest.mark.parametrize('order', range(0, 6))
822
+ def test_affine_transform21(self, order, xp):
823
+ data = [[1, 2, 3, 4],
824
+ [5, 6, 7, 8],
825
+ [9, 10, 11, 12]]
826
+ data = xp.asarray(data)
827
+ out = ndimage.affine_transform(data, xp.asarray([[2], [0]]), 0, (2,),
828
+ order=order)
829
+ assert_array_almost_equal(out, xp.asarray([1, 9]))
830
+
831
+ @pytest.mark.parametrize('order', range(0, 6))
832
+ def test_affine_transform22(self, order, xp):
833
+ # shift and offset interaction; see issue #1547
834
+ data = xp.asarray([4, 1, 3, 2])
835
+ out = ndimage.affine_transform(data, xp.asarray([[2]]), [-1], (3,),
836
+ order=order)
837
+ assert_array_almost_equal(out, xp.asarray([0, 1, 2]))
838
+
839
+ @pytest.mark.parametrize('order', range(0, 6))
840
+ def test_affine_transform23(self, order, xp):
841
+ # shift and offset interaction; see issue #1547
842
+ data = xp.asarray([4, 1, 3, 2])
843
+ out = ndimage.affine_transform(data, xp.asarray([[0.5]]), [-1], (8,),
844
+ order=order)
845
+ assert_array_almost_equal(out[::2], xp.asarray([0, 4, 1, 3]))
846
+
847
+ @pytest.mark.parametrize('order', range(0, 6))
848
+ def test_affine_transform24(self, order, xp):
849
+ # consistency between diagonal and non-diagonal case; see issue #1547
850
+ data = xp.asarray([4, 1, 3, 2])
851
+ with warnings.catch_warnings():
852
+ warnings.filterwarnings(
853
+ "ignore",
854
+ 'The behavior of affine_transform with a 1-D array .* has changed',
855
+ UserWarning)
856
+ out1 = ndimage.affine_transform(data, xp.asarray([2]), -1, order=order)
857
+ out2 = ndimage.affine_transform(data, xp.asarray([[2]]), -1, order=order)
858
+ assert_array_almost_equal(out1, out2)
859
+
860
+ @pytest.mark.parametrize('order', range(0, 6))
861
+ def test_affine_transform25(self, order, xp):
862
+ # consistency between diagonal and non-diagonal case; see issue #1547
863
+ data = xp.asarray([4, 1, 3, 2])
864
+ with warnings.catch_warnings():
865
+ warnings.filterwarnings("ignore",
866
+ 'The behavior of affine_transform with a 1-D array .* '
867
+ 'has changed', UserWarning)
868
+ out1 = ndimage.affine_transform(data, xp.asarray([0.5]), -1, order=order)
869
+ out2 = ndimage.affine_transform(data, xp.asarray([[0.5]]), -1, order=order)
870
+ assert_array_almost_equal(out1, out2)
871
+
872
+ @pytest.mark.parametrize('order', range(0, 6))
873
+ def test_affine_transform26(self, order, xp):
874
+ # test homogeneous coordinates
875
+ data = xp.asarray([[4, 1, 3, 2],
876
+ [7, 6, 8, 5],
877
+ [3, 5, 3, 6]])
878
+ if (order > 1):
879
+ filtered = ndimage.spline_filter(data, order=order)
880
+ else:
881
+ filtered = data
882
+ tform_original = xp.eye(2)
883
+ offset_original = -xp.ones((2, 1))
884
+
885
+ tform_h1 = xp.concat((tform_original, offset_original), axis=1) # hstack
886
+ tform_h2 = xp.concat((tform_h1, xp.asarray([[0.0, 0, 1]])), axis=0) # vstack
887
+
888
+ offs = [float(x) for x in xp.reshape(offset_original, (-1,))]
889
+
890
+ out1 = ndimage.affine_transform(filtered, tform_original,
891
+ offs,
892
+ order=order, prefilter=False)
893
+ out2 = ndimage.affine_transform(filtered, tform_h1, order=order,
894
+ prefilter=False)
895
+ out3 = ndimage.affine_transform(filtered, tform_h2, order=order,
896
+ prefilter=False)
897
+ for out in [out1, out2, out3]:
898
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
899
+ [0, 4, 1, 3],
900
+ [0, 7, 6, 8]]))
901
+
902
+ @xfail_xp_backends("cupy", reason="does not raise")
903
+ def test_affine_transform27(self, xp):
904
+ # test valid homogeneous transformation matrix
905
+ data = xp.asarray([[4, 1, 3, 2],
906
+ [7, 6, 8, 5],
907
+ [3, 5, 3, 6]])
908
+ tform_h1 = xp.concat((xp.eye(2), -xp.ones((2, 1))) , axis=1) # vstack
909
+ tform_h2 = xp.concat((tform_h1, xp.asarray([[5.0, 2, 1]])), axis=0) # hstack
910
+
911
+ assert_raises(ValueError, ndimage.affine_transform, data, tform_h2)
912
+
913
+ @skip_xp_backends(np_only=True, reason='byteorder is numpy-specific')
914
+ def test_affine_transform_1d_endianness_with_output_parameter(self, xp):
915
+ # 1d affine transform given output ndarray or dtype with
916
+ # either endianness. see issue #7388
917
+ data = xp.ones((2, 2))
918
+ for out in [xp.empty_like(data),
919
+ xp.empty_like(data).astype(data.dtype.newbyteorder()),
920
+ data.dtype, data.dtype.newbyteorder()]:
921
+ with warnings.catch_warnings():
922
+ warnings.filterwarnings("ignore",
923
+ 'The behavior of affine_transform with a 1-D array '
924
+ '.* has changed', UserWarning)
925
+ matrix = xp.asarray([1, 1])
926
+ returned = ndimage.affine_transform(data, matrix, output=out)
927
+ result = out if returned is None else returned
928
+ assert_array_almost_equal(result, xp.asarray([[1, 1], [1, 1]]))
929
+
930
+ @skip_xp_backends(np_only=True, reason='byteorder is numpy-specific')
931
+ def test_affine_transform_multi_d_endianness_with_output_parameter(self, xp):
932
+ # affine transform given output ndarray or dtype with either endianness
933
+ # see issue #4127
934
+ # NB: byteorder is numpy-specific
935
+ data = np.asarray([1])
936
+ for out in [data.dtype, data.dtype.newbyteorder(),
937
+ np.empty_like(data),
938
+ np.empty_like(data).astype(data.dtype.newbyteorder())]:
939
+ returned = ndimage.affine_transform(data, np.asarray([[1]]), output=out)
940
+ result = out if returned is None else returned
941
+ assert_array_almost_equal(result, np.asarray([1]))
942
+
943
+ @skip_xp_backends(np_only=True,
944
+ reason='`out` of a different size is numpy-specific'
945
+ )
946
+ def test_affine_transform_output_shape(self, xp):
947
+ # don't require output_shape when out of a different size is given
948
+ data = xp.arange(8, dtype=xp.float64)
949
+ out = xp.ones((16,))
950
+
951
+ ndimage.affine_transform(data, xp.asarray([[1]]), output=out)
952
+ assert_array_almost_equal(out[:8], data)
953
+
954
+ # mismatched output shape raises an error
955
+ with pytest.raises(RuntimeError):
956
+ ndimage.affine_transform(
957
+ data, [[1]], output=out, output_shape=(12,))
958
+
959
+ @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
960
+ def test_affine_transform_with_string_output(self, xp):
961
+ data = xp.asarray([1])
962
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), output='f')
963
+ assert out.dtype is np.dtype('f')
964
+ assert_array_almost_equal(out, xp.asarray([1]))
965
+
966
+ @pytest.mark.parametrize('shift',
967
+ [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
968
+ @pytest.mark.parametrize('order', range(0, 6))
969
+ def test_affine_transform_shift_via_grid_wrap(self, shift, order, xp):
970
+ # For mode 'grid-wrap', integer shifts should match np.roll
971
+ x = np.asarray([[0, 1],
972
+ [2, 3]])
973
+ affine = np.zeros((2, 3))
974
+ affine[:2, :2] = np.eye(2)
975
+ affine[:, 2] = np.asarray(shift)
976
+
977
+ expected = np.roll(x, shift, axis=(0, 1))
978
+
979
+ x = xp.asarray(x)
980
+ affine = xp.asarray(affine)
981
+ expected = xp.asarray(expected)
982
+
983
+ assert_array_almost_equal(
984
+ ndimage.affine_transform(x, affine, mode='grid-wrap', order=order),
985
+ expected
986
+ )
987
+
988
+ @pytest.mark.parametrize('order', range(0, 6))
989
+ def test_affine_transform_shift_reflect(self, order, xp):
990
+ # shift by x.shape results in reflection
991
+ x = np.asarray([[0, 1, 2],
992
+ [3, 4, 5]])
993
+ expected = x[::-1, ::-1].copy() # strides >0 for torch
994
+ x = xp.asarray(x)
995
+ expected = xp.asarray(expected)
996
+
997
+ affine = np.zeros([2, 3])
998
+ affine[:2, :2] = np.eye(2)
999
+ affine[:, 2] = np.asarray(x.shape)
1000
+ affine = xp.asarray(affine)
1001
+
1002
+ assert_array_almost_equal(
1003
+ ndimage.affine_transform(x, affine, mode='reflect', order=order),
1004
+ expected,
1005
+ )
1006
+
1007
+
1008
+ @make_xp_test_case(ndimage.shift)
1009
+ class TestShift:
1010
+
1011
+ @pytest.mark.parametrize('order', range(0, 6))
1012
+ def test_shift01(self, order, xp):
1013
+ data = xp.asarray([1])
1014
+ out = ndimage.shift(data, [1], order=order)
1015
+ assert_array_almost_equal(out, xp.asarray([0]))
1016
+
1017
+ @pytest.mark.parametrize('order', range(0, 6))
1018
+ def test_shift02(self, order, xp):
1019
+ data = xp.ones([4])
1020
+ out = ndimage.shift(data, [1], order=order)
1021
+ assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1]))
1022
+
1023
+ @pytest.mark.parametrize('order', range(0, 6))
1024
+ def test_shift03(self, order, xp):
1025
+ data = xp.ones([4])
1026
+ out = ndimage.shift(data, -1, order=order)
1027
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0]))
1028
+
1029
+ @pytest.mark.parametrize('order', range(0, 6))
1030
+ def test_shift04(self, order, xp):
1031
+ data = xp.asarray([4, 1, 3, 2])
1032
+ out = ndimage.shift(data, 1, order=order)
1033
+ assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3]))
1034
+
1035
+ @pytest.mark.parametrize('order', range(0, 6))
1036
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
1037
+ def test_shift05(self, order, dtype, xp):
1038
+ dtype = getattr(xp, dtype)
1039
+ data = xp.asarray([[1, 1, 1, 1],
1040
+ [1, 1, 1, 1],
1041
+ [1, 1, 1, 1]], dtype=dtype)
1042
+ expected = xp.asarray([[0, 1, 1, 1],
1043
+ [0, 1, 1, 1],
1044
+ [0, 1, 1, 1]], dtype=dtype)
1045
+ if xp.isdtype(data.dtype, 'complex floating'):
1046
+ data -= 1j * data
1047
+ expected -= 1j * expected
1048
+ out = ndimage.shift(data, [0, 1], order=order)
1049
+ assert_array_almost_equal(out, expected)
1050
+
1051
+ @pytest.mark.parametrize('order', range(0, 6))
1052
+ @pytest.mark.parametrize('mode', ['constant', 'grid-constant'])
1053
+ @pytest.mark.parametrize('dtype', ['float64', 'complex128'])
1054
+ def test_shift_with_nonzero_cval(self, order, mode, dtype, xp):
1055
+ data = np.asarray([[1, 1, 1, 1],
1056
+ [1, 1, 1, 1],
1057
+ [1, 1, 1, 1]], dtype=dtype)
1058
+
1059
+ expected = np.asarray([[0, 1, 1, 1],
1060
+ [0, 1, 1, 1],
1061
+ [0, 1, 1, 1]], dtype=dtype)
1062
+
1063
+ if np_compat.isdtype(data.dtype, 'complex floating'):
1064
+ data -= 1j * data
1065
+ expected -= 1j * expected
1066
+ cval = 5.0
1067
+ expected[:, 0] = cval # specific to shift of [0, 1] used below
1068
+
1069
+ data = xp.asarray(data)
1070
+ expected = xp.asarray(expected)
1071
+ out = ndimage.shift(data, [0, 1], order=order, mode=mode, cval=cval)
1072
+ assert_array_almost_equal(out, expected)
1073
+
1074
+ @pytest.mark.parametrize('order', range(0, 6))
1075
+ def test_shift06(self, order, xp):
1076
+ data = xp.asarray([[4, 1, 3, 2],
1077
+ [7, 6, 8, 5],
1078
+ [3, 5, 3, 6]])
1079
+ out = ndimage.shift(data, [0, 1], order=order)
1080
+ assert_array_almost_equal(out, xp.asarray([[0, 4, 1, 3],
1081
+ [0, 7, 6, 8],
1082
+ [0, 3, 5, 3]]))
1083
+
1084
+ @pytest.mark.parametrize('order', range(0, 6))
1085
+ def test_shift07(self, order, xp):
1086
+ data = xp.asarray([[4, 1, 3, 2],
1087
+ [7, 6, 8, 5],
1088
+ [3, 5, 3, 6]])
1089
+ out = ndimage.shift(data, [1, 0], order=order)
1090
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
1091
+ [4, 1, 3, 2],
1092
+ [7, 6, 8, 5]]))
1093
+
1094
+ @pytest.mark.parametrize('order', range(0, 6))
1095
+ def test_shift08(self, order, xp):
1096
+ data = xp.asarray([[4, 1, 3, 2],
1097
+ [7, 6, 8, 5],
1098
+ [3, 5, 3, 6]])
1099
+ out = ndimage.shift(data, [1, 1], order=order)
1100
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
1101
+ [0, 4, 1, 3],
1102
+ [0, 7, 6, 8]]))
1103
+
1104
+ @pytest.mark.parametrize('order', range(0, 6))
1105
+ def test_shift09(self, order, xp):
1106
+ data = xp.asarray([[4, 1, 3, 2],
1107
+ [7, 6, 8, 5],
1108
+ [3, 5, 3, 6]])
1109
+ if (order > 1):
1110
+ filtered = ndimage.spline_filter(data, order=order)
1111
+ else:
1112
+ filtered = data
1113
+ out = ndimage.shift(filtered, [1, 1], order=order, prefilter=False)
1114
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
1115
+ [0, 4, 1, 3],
1116
+ [0, 7, 6, 8]]))
1117
+
1118
+ @pytest.mark.parametrize('shift',
1119
+ [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
1120
+ @pytest.mark.parametrize('order', range(0, 6))
1121
+ def test_shift_grid_wrap(self, shift, order, xp):
1122
+ # For mode 'grid-wrap', integer shifts should match np.roll
1123
+ x = np.asarray([[0, 1],
1124
+ [2, 3]])
1125
+ expected = np.roll(x, shift, axis=(0,1))
1126
+
1127
+ x = xp.asarray(x)
1128
+ expected = xp.asarray(expected)
1129
+
1130
+ assert_array_almost_equal(
1131
+ ndimage.shift(x, shift, mode='grid-wrap', order=order),
1132
+ expected
1133
+ )
1134
+
1135
+ @pytest.mark.parametrize('shift',
1136
+ [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
1137
+ @pytest.mark.parametrize('order', range(0, 6))
1138
+ def test_shift_grid_constant1(self, shift, order, xp):
1139
+ # For integer shifts, 'constant' and 'grid-constant' should be equal
1140
+ x = xp.reshape(xp.arange(20), (5, 4))
1141
+ assert_array_almost_equal(
1142
+ ndimage.shift(x, shift, mode='grid-constant', order=order),
1143
+ ndimage.shift(x, shift, mode='constant', order=order),
1144
+ )
1145
+
1146
+ def test_shift_grid_constant_order1(self, xp):
1147
+ x = xp.asarray([[1, 2, 3],
1148
+ [4, 5, 6]], dtype=xp.float64)
1149
+ expected_result = xp.asarray([[0.25, 0.75, 1.25],
1150
+ [1.25, 3.00, 4.00]])
1151
+ assert_array_almost_equal(
1152
+ ndimage.shift(x, (0.5, 0.5), mode='grid-constant', order=1),
1153
+ expected_result,
1154
+ )
1155
+
1156
+ @pytest.mark.parametrize('order', range(0, 6))
1157
+ def test_shift_reflect(self, order, xp):
1158
+ # shift by x.shape results in reflection
1159
+ x = np.asarray([[0, 1, 2],
1160
+ [3, 4, 5]])
1161
+ expected = x[::-1, ::-1].copy() # strides > 0 for torch
1162
+
1163
+ x = xp.asarray(x)
1164
+ expected = xp.asarray(expected)
1165
+ assert_array_almost_equal(
1166
+ ndimage.shift(x, x.shape, mode='reflect', order=order),
1167
+ expected,
1168
+ )
1169
+
1170
+ @pytest.mark.parametrize('order', range(0, 6))
1171
+ @pytest.mark.parametrize('prefilter', [False, True])
1172
+ def test_shift_nearest_boundary(self, order, prefilter, xp):
1173
+ # verify that shifting at least order // 2 beyond the end of the array
1174
+ # gives a value equal to the edge value.
1175
+ x = xp.arange(16)
1176
+ kwargs = dict(mode='nearest', order=order, prefilter=prefilter)
1177
+ assert_array_almost_equal(
1178
+ ndimage.shift(x, order // 2 + 1, **kwargs)[0], x[0],
1179
+ )
1180
+ assert_array_almost_equal(
1181
+ ndimage.shift(x, -order // 2 - 1, **kwargs)[-1], x[-1],
1182
+ )
1183
+
1184
+ @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest',
1185
+ 'mirror', 'reflect'])
1186
+ @pytest.mark.parametrize('order', range(6))
1187
+ def test_shift_vs_padded(self, order, mode, xp):
1188
+ x_np = np.arange(144, dtype=float).reshape(12, 12)
1189
+ shift = (0.4, -2.3)
1190
+
1191
+ # manually pad and then extract center to get expected result
1192
+ npad = 32
1193
+ pad_mode = ndimage_to_numpy_mode.get(mode)
1194
+ x_padded = xp.asarray(np.pad(x_np, npad, mode=pad_mode))
1195
+ x = xp.asarray(x_np)
1196
+
1197
+ center_slice = tuple([slice(npad, -npad)] * x.ndim)
1198
+ expected_result = ndimage.shift(
1199
+ x_padded, shift, mode=mode, order=order)[center_slice]
1200
+
1201
+ xp_assert_close(
1202
+ ndimage.shift(x, shift, mode=mode, order=order),
1203
+ expected_result,
1204
+ rtol=1e-7,
1205
+ )
1206
+
1207
+
1208
+ @make_xp_test_case(ndimage.zoom)
1209
+ class TestZoom:
1210
+
1211
+ @pytest.mark.parametrize('order', range(0, 6))
1212
+ def test_zoom1(self, order, xp):
1213
+ for z in [2, [2, 2]]:
1214
+ arr = xp.reshape(xp.arange(25, dtype=xp.float64), (5, 5))
1215
+ arr = ndimage.zoom(arr, z, order=order)
1216
+ assert arr.shape == (10, 10)
1217
+ assert xp.all(arr[-1, :] != 0)
1218
+ assert xp.all(arr[-1, :] >= (20 - eps))
1219
+ assert xp.all(arr[0, :] <= (5 + eps))
1220
+ assert xp.all(arr >= (0 - eps))
1221
+ assert xp.all(arr <= (24 + eps))
1222
+
1223
+ def test_zoom2(self, xp):
1224
+ arr = xp.reshape(xp.arange(12), (3, 4))
1225
+ out = ndimage.zoom(ndimage.zoom(arr, 2), 0.5)
1226
+ xp_assert_equal(out, arr)
1227
+
1228
+ def test_zoom3(self, xp):
1229
+ arr = xp.asarray([[1, 2]])
1230
+ out1 = ndimage.zoom(arr, (2, 1))
1231
+ out2 = ndimage.zoom(arr, (1, 2))
1232
+
1233
+ assert_array_almost_equal(out1, xp.asarray([[1, 2], [1, 2]]))
1234
+ assert_array_almost_equal(out2, xp.asarray([[1, 1, 2, 2]]))
1235
+
1236
+ @pytest.mark.parametrize('order', range(0, 6))
1237
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
1238
+ def test_zoom_affine01(self, order, dtype, xp):
1239
+ dtype = getattr(xp, dtype)
1240
+ data = xp.asarray([[1, 2, 3, 4],
1241
+ [5, 6, 7, 8],
1242
+ [9, 10, 11, 12]], dtype=dtype)
1243
+ if xp.isdtype(data.dtype, 'complex floating'):
1244
+ data -= 1j * data
1245
+ with warnings.catch_warnings():
1246
+ warnings.filterwarnings("ignore",
1247
+ 'The behavior of affine_transform with a 1-D array .* '
1248
+ 'has changed', UserWarning)
1249
+ out = ndimage.affine_transform(data, xp.asarray([0.5, 0.5]), 0,
1250
+ (6, 8), order=order)
1251
+ assert_array_almost_equal(out[::2, ::2], data)
1252
+
1253
+ def test_zoom_infinity(self, xp):
1254
+ # Ticket #1419 regression test
1255
+ dim = 8
1256
+ ndimage.zoom(xp.zeros((dim, dim)), 1. / dim, mode='nearest')
1257
+
1258
+ def test_zoom_zoomfactor_one(self, xp):
1259
+ # Ticket #1122 regression test
1260
+ arr = xp.zeros((1, 5, 5))
1261
+ zoom = (1.0, 2.0, 2.0)
1262
+
1263
+ out = ndimage.zoom(arr, zoom, cval=7)
1264
+ ref = xp.zeros((1, 10, 10))
1265
+ assert_array_almost_equal(out, ref)
1266
+
1267
+ def test_zoom_output_shape_roundoff(self, xp):
1268
+ arr = xp.zeros((3, 11, 25))
1269
+ zoom = (4.0 / 3, 15.0 / 11, 29.0 / 25)
1270
+ out = ndimage.zoom(arr, zoom)
1271
+ assert out.shape == (4, 15, 29)
1272
+
1273
+ @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)])
1274
+ @pytest.mark.parametrize('mode', ['nearest', 'constant', 'wrap', 'reflect',
1275
+ 'mirror', 'grid-wrap', 'grid-mirror',
1276
+ 'grid-constant'])
1277
+ def test_zoom_by_int_order0(self, zoom, mode, xp):
1278
+ # order 0 zoom should be the same as replication via np.kron
1279
+ # Note: This is not True for general x shapes when grid_mode is False,
1280
+ # but works here for all modes because the size ratio happens to
1281
+ # always be an integer when x.shape = (2, 2).
1282
+ x_np = np.asarray([[0, 1],
1283
+ [2, 3]], dtype=np.float64)
1284
+ expected = np.kron(x_np, np.ones(zoom))
1285
+
1286
+ x = xp.asarray(x_np)
1287
+ expected = xp.asarray(expected)
1288
+
1289
+ assert_array_almost_equal(
1290
+ ndimage.zoom(x, zoom, order=0, mode=mode),
1291
+ expected
1292
+ )
1293
+
1294
+ @pytest.mark.parametrize('shape', [(2, 3), (4, 4)])
1295
+ @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)])
1296
+ @pytest.mark.parametrize('mode', ['nearest', 'reflect', 'mirror',
1297
+ 'grid-wrap', 'grid-constant'])
1298
+ def test_zoom_grid_by_int_order0(self, shape, zoom, mode, xp):
1299
+ # When grid_mode is True, order 0 zoom should be the same as
1300
+ # replication via np.kron. The only exceptions to this are the
1301
+ # non-grid modes 'constant' and 'wrap'.
1302
+ x_np = np.arange(np.prod(shape), dtype=float).reshape(shape)
1303
+
1304
+ x = xp.asarray(x_np)
1305
+ assert_array_almost_equal(
1306
+ ndimage.zoom(x, zoom, order=0, mode=mode, grid_mode=True),
1307
+ xp.asarray(np.kron(x_np, np.ones(zoom)))
1308
+ )
1309
+
1310
+ @pytest.mark.parametrize('mode', ['constant', 'wrap'])
1311
+ def test_zoom_grid_mode_warnings(self, mode, xp):
1312
+ # Warn on use of non-grid modes when grid_mode is True
1313
+ x = xp.reshape(xp.arange(9, dtype=xp.float64), (3, 3))
1314
+ with pytest.warns(UserWarning,
1315
+ match="It is recommended to use mode"):
1316
+ ndimage.zoom(x, 2, mode=mode, grid_mode=True),
1317
+
1318
+ @skip_xp_backends("dask.array", reason="output=array requires buffer view")
1319
+ @skip_xp_backends("jax.numpy", reason="output=array requires buffer view")
1320
+ def test_zoom_output_shape(self, xp):
1321
+ """Ticket #643"""
1322
+ x = xp.reshape(xp.arange(12), (3, 4))
1323
+ ndimage.zoom(x, 2, output=xp.zeros((6, 8)))
1324
+
1325
+ def test_zoom_0d_array(self, xp):
1326
+ # Ticket #21670 regression test
1327
+ a = xp.arange(10.)
1328
+ factor = 2
1329
+ actual = ndimage.zoom(a, np.array(factor))
1330
+ expected = ndimage.zoom(a, factor)
1331
+ xp_assert_close(actual, expected)
1332
+
1333
+ @xfail_xp_backends("cupy", reason="CuPy `zoom` needs similar fix.")
1334
+ def test_zoom_1_gh20999(self, xp):
1335
+ # gh-20999 reported that zoom with `zoom=1` (or sequence of ones)
1336
+ # introduced noise. Check that this is resolved.
1337
+ x = xp.eye(3)
1338
+ xp_assert_equal(ndimage.zoom(x, 1), x)
1339
+ xp_assert_equal(ndimage.zoom(x, (1, 1)), x)
1340
+
1341
+ @xfail_xp_backends("cupy", reason="CuPy `zoom` needs similar fix.")
1342
+ @skip_xp_backends("jax.numpy", reason="read-only backend")
1343
+ @xfail_xp_backends("dask.array", reason="numpy round-trip")
1344
+ def test_zoom_1_gh20999_output(self, xp):
1345
+ x = xp.eye(3)
1346
+ output = xp.zeros_like(x)
1347
+ ndimage.zoom(x, 1, output=output)
1348
+ xp_assert_equal(output, x)
1349
+
1350
+
1351
+ @make_xp_test_case(ndimage.rotate)
1352
+ class TestRotate:
1353
+
1354
+ @pytest.mark.parametrize('order', range(0, 6))
1355
+ def test_rotate01(self, order, xp):
1356
+ data = xp.asarray([[0, 0, 0, 0],
1357
+ [0, 1, 1, 0],
1358
+ [0, 0, 0, 0]], dtype=xp.float64)
1359
+ out = ndimage.rotate(data, 0, order=order)
1360
+ assert_array_almost_equal(out, data)
1361
+
1362
+ @pytest.mark.parametrize('order', range(0, 6))
1363
+ def test_rotate02(self, order, xp):
1364
+ data = xp.asarray([[0, 0, 0, 0],
1365
+ [0, 1, 0, 0],
1366
+ [0, 0, 0, 0]], dtype=xp.float64)
1367
+ expected = xp.asarray([[0, 0, 0],
1368
+ [0, 0, 0],
1369
+ [0, 1, 0],
1370
+ [0, 0, 0]], dtype=xp.float64)
1371
+ out = ndimage.rotate(data, 90, order=order)
1372
+ assert_array_almost_equal(out, expected)
1373
+
1374
+ @pytest.mark.parametrize('order', range(0, 6))
1375
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
1376
+ def test_rotate03(self, order, dtype, xp):
1377
+ dtype = getattr(xp, dtype)
1378
+ data = xp.asarray([[0, 0, 0, 0, 0],
1379
+ [0, 1, 1, 0, 0],
1380
+ [0, 0, 0, 0, 0]], dtype=dtype)
1381
+ expected = xp.asarray([[0, 0, 0],
1382
+ [0, 0, 0],
1383
+ [0, 1, 0],
1384
+ [0, 1, 0],
1385
+ [0, 0, 0]], dtype=dtype)
1386
+ if xp.isdtype(data.dtype, 'complex floating'):
1387
+ data -= 1j * data
1388
+ expected -= 1j * expected
1389
+ out = ndimage.rotate(data, 90, order=order)
1390
+ assert_array_almost_equal(out, expected)
1391
+
1392
+ @pytest.mark.parametrize('order', range(0, 6))
1393
+ def test_rotate04(self, order, xp):
1394
+ data = xp.asarray([[0, 0, 0, 0, 0],
1395
+ [0, 1, 1, 0, 0],
1396
+ [0, 0, 0, 0, 0]], dtype=xp.float64)
1397
+ expected = xp.asarray([[0, 0, 0, 0, 0],
1398
+ [0, 0, 1, 0, 0],
1399
+ [0, 0, 1, 0, 0]], dtype=xp.float64)
1400
+ out = ndimage.rotate(data, 90, reshape=False, order=order)
1401
+ assert_array_almost_equal(out, expected)
1402
+
1403
+ @pytest.mark.parametrize('order', range(0, 6))
1404
+ def test_rotate05(self, order, xp):
1405
+ data = np.empty((4, 3, 3))
1406
+ for i in range(3):
1407
+ data[:, :, i] = np.asarray([[0, 0, 0],
1408
+ [0, 1, 0],
1409
+ [0, 1, 0],
1410
+ [0, 0, 0]], dtype=np.float64)
1411
+ data = xp.asarray(data)
1412
+ expected = xp.asarray([[0, 0, 0, 0],
1413
+ [0, 1, 1, 0],
1414
+ [0, 0, 0, 0]], dtype=xp.float64)
1415
+ out = ndimage.rotate(data, 90, order=order)
1416
+ for i in range(3):
1417
+ assert_array_almost_equal(out[:, :, i], expected)
1418
+
1419
+ @pytest.mark.parametrize('order', range(0, 6))
1420
+ def test_rotate06(self, order, xp):
1421
+ data = np.empty((3, 4, 3))
1422
+ for i in range(3):
1423
+ data[:, :, i] = np.asarray([[0, 0, 0, 0],
1424
+ [0, 1, 1, 0],
1425
+ [0, 0, 0, 0]], dtype=np.float64)
1426
+ data = xp.asarray(data)
1427
+ expected = xp.asarray([[0, 0, 0],
1428
+ [0, 1, 0],
1429
+ [0, 1, 0],
1430
+ [0, 0, 0]], dtype=xp.float64)
1431
+ out = ndimage.rotate(data, 90, order=order)
1432
+ for i in range(3):
1433
+ assert_array_almost_equal(out[:, :, i], expected)
1434
+
1435
+ @pytest.mark.parametrize('order', range(0, 6))
1436
+ def test_rotate07(self, order, xp):
1437
+ data = xp.asarray([[[0, 0, 0, 0, 0],
1438
+ [0, 1, 1, 0, 0],
1439
+ [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
1440
+ data = xp.permute_dims(data, (2, 1, 0))
1441
+ expected = xp.asarray([[[0, 0, 0],
1442
+ [0, 1, 0],
1443
+ [0, 1, 0],
1444
+ [0, 0, 0],
1445
+ [0, 0, 0]]] * 2, dtype=xp.float64)
1446
+ expected = xp.permute_dims(expected, (2, 1, 0))
1447
+ out = ndimage.rotate(data, 90, axes=(0, 1), order=order)
1448
+ assert_array_almost_equal(out, expected)
1449
+
1450
+ @pytest.mark.parametrize('order', range(0, 6))
1451
+ def test_rotate08(self, order, xp):
1452
+ data = xp.asarray([[[0, 0, 0, 0, 0],
1453
+ [0, 1, 1, 0, 0],
1454
+ [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
1455
+ data = xp.permute_dims(data, (2, 1, 0)) # == np.transpose
1456
+ expected = xp.asarray([[[0, 0, 1, 0, 0],
1457
+ [0, 0, 1, 0, 0],
1458
+ [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
1459
+ expected = xp.permute_dims(expected, (2, 1, 0))
1460
+ out = ndimage.rotate(data, 90, axes=(0, 1), reshape=False, order=order)
1461
+ assert_array_almost_equal(out, expected)
1462
+
1463
+ def test_rotate09(self, xp):
1464
+ data = xp.asarray([[0, 0, 0, 0, 0],
1465
+ [0, 1, 1, 0, 0],
1466
+ [0, 0, 0, 0, 0]] * 2, dtype=xp.float64)
1467
+ with assert_raises(ValueError):
1468
+ ndimage.rotate(data, 90, axes=(0, data.ndim))
1469
+
1470
+ def test_rotate10(self, xp):
1471
+ data = xp.reshape(xp.arange(45, dtype=xp.float64), (3, 5, 3))
1472
+
1473
+ # The output of ndimage.rotate before refactoring
1474
+ expected = xp.asarray([[[0.0, 0.0, 0.0],
1475
+ [0.0, 0.0, 0.0],
1476
+ [6.54914793, 7.54914793, 8.54914793],
1477
+ [10.84520162, 11.84520162, 12.84520162],
1478
+ [0.0, 0.0, 0.0]],
1479
+ [[6.19286575, 7.19286575, 8.19286575],
1480
+ [13.4730712, 14.4730712, 15.4730712],
1481
+ [21.0, 22.0, 23.0],
1482
+ [28.5269288, 29.5269288, 30.5269288],
1483
+ [35.80713425, 36.80713425, 37.80713425]],
1484
+ [[0.0, 0.0, 0.0],
1485
+ [31.15479838, 32.15479838, 33.15479838],
1486
+ [35.45085207, 36.45085207, 37.45085207],
1487
+ [0.0, 0.0, 0.0],
1488
+ [0.0, 0.0, 0.0]]], dtype=xp.float64)
1489
+
1490
+ out = ndimage.rotate(data, angle=12, reshape=False)
1491
+ #assert_array_almost_equal(out, expected)
1492
+ xp_assert_close(out, expected, rtol=1e-6, atol=2e-6)
1493
+
1494
+
1495
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8400")
1496
+ def test_rotate_exact_180(self, xp):
1497
+ a = xp.asarray(np.tile(np.arange(5), (5, 1)))
1498
+ b = ndimage.rotate(ndimage.rotate(a, 180), -180)
1499
+ xp_assert_equal(a, b)
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_measurements.py ADDED
@@ -0,0 +1,1696 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import os.path
3
+ import warnings
4
+
5
+ import numpy as np
6
+
7
+ from scipy._lib._array_api import (
8
+ is_torch,
9
+ xp_assert_equal,
10
+ xp_assert_close,
11
+ assert_array_almost_equal,
12
+ assert_almost_equal,
13
+ make_xp_test_case,
14
+ )
15
+
16
+ import pytest
17
+ from pytest import raises as assert_raises
18
+
19
+ import scipy.ndimage as ndimage
20
+
21
+ from . import types
22
+
23
+ skip_xp_backends = pytest.mark.skip_xp_backends
24
+
25
+ IS_WINDOWS_AND_NP1 = os.name == 'nt' and np.__version__ < '2'
26
+
27
+
28
+ @skip_xp_backends(np_only=True, reason='test internal numpy-only helpers')
29
+ class Test_measurements_stats:
30
+ """ndimage._measurements._stats() is a utility used by other functions.
31
+
32
+ Since internal ndimage/_measurements.py code is NumPy-only,
33
+ so is this this test class.
34
+ """
35
+ def test_a(self, xp):
36
+ x = [0, 1, 2, 6]
37
+ labels = [0, 0, 1, 1]
38
+ index = [0, 1]
39
+ for shp in [(4,), (2, 2)]:
40
+ x = np.array(x).reshape(shp)
41
+ labels = np.array(labels).reshape(shp)
42
+ counts, sums = ndimage._measurements._stats(
43
+ x, labels=labels, index=index)
44
+
45
+ dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
46
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
47
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
48
+
49
+ def test_b(self, xp):
50
+ # Same data as test_a, but different labels. The label 9 exceeds the
51
+ # length of 'labels', so this test will follow a different code path.
52
+ x = [0, 1, 2, 6]
53
+ labels = [0, 0, 9, 9]
54
+ index = [0, 9]
55
+ for shp in [(4,), (2, 2)]:
56
+ x = np.array(x).reshape(shp)
57
+ labels = np.array(labels).reshape(shp)
58
+ counts, sums = ndimage._measurements._stats(
59
+ x, labels=labels, index=index)
60
+
61
+ dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
62
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
63
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
64
+
65
+ def test_a_centered(self, xp):
66
+ x = [0, 1, 2, 6]
67
+ labels = [0, 0, 1, 1]
68
+ index = [0, 1]
69
+ for shp in [(4,), (2, 2)]:
70
+ x = np.array(x).reshape(shp)
71
+ labels = np.array(labels).reshape(shp)
72
+ counts, sums, centers = ndimage._measurements._stats(
73
+ x, labels=labels, index=index, centered=True)
74
+
75
+ dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
76
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
77
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
78
+ xp_assert_equal(centers, np.asarray([0.5, 8.0]))
79
+
80
+ def test_b_centered(self, xp):
81
+ x = [0, 1, 2, 6]
82
+ labels = [0, 0, 9, 9]
83
+ index = [0, 9]
84
+ for shp in [(4,), (2, 2)]:
85
+ x = np.array(x).reshape(shp)
86
+ labels = np.array(labels).reshape(shp)
87
+ counts, sums, centers = ndimage._measurements._stats(
88
+ x, labels=labels, index=index, centered=True)
89
+
90
+ dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
91
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
92
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
93
+ xp_assert_equal(centers, np.asarray([0.5, 8.0]))
94
+
95
+ def test_nonint_labels(self, xp):
96
+ x = [0, 1, 2, 6]
97
+ labels = [0.0, 0.0, 9.0, 9.0]
98
+ index = [0.0, 9.0]
99
+ for shp in [(4,), (2, 2)]:
100
+ x = np.array(x).reshape(shp)
101
+ labels = np.array(labels).reshape(shp)
102
+ counts, sums, centers = ndimage._measurements._stats(
103
+ x, labels=labels, index=index, centered=True)
104
+
105
+ dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
106
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
107
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
108
+ xp_assert_equal(centers, np.asarray([0.5, 8.0]))
109
+
110
+
111
+ @skip_xp_backends(np_only=True, reason='test internal numpy-only helpers')
112
+ class Test_measurements_select:
113
+ """ndimage._measurements._select() is a utility used by other functions."""
114
+
115
+ def test_basic(self, xp):
116
+ x = [0, 1, 6, 2]
117
+ cases = [
118
+ ([0, 0, 1, 1], [0, 1]), # "Small" integer labels
119
+ ([0, 0, 9, 9], [0, 9]), # A label larger than len(labels)
120
+ ([0.0, 0.0, 7.0, 7.0], [0.0, 7.0]), # Non-integer labels
121
+ ]
122
+ for labels, index in cases:
123
+ result = ndimage._measurements._select(
124
+ x, labels=labels, index=index)
125
+ assert len(result) == 0
126
+ result = ndimage._measurements._select(
127
+ x, labels=labels, index=index, find_max=True)
128
+ assert len(result) == 1
129
+ xp_assert_equal(result[0], [1, 6])
130
+ result = ndimage._measurements._select(
131
+ x, labels=labels, index=index, find_min=True)
132
+ assert len(result) == 1
133
+ xp_assert_equal(result[0], [0, 2])
134
+ result = ndimage._measurements._select(
135
+ x, labels=labels, index=index, find_min=True,
136
+ find_min_positions=True)
137
+ assert len(result) == 2
138
+ xp_assert_equal(result[0], [0, 2])
139
+ xp_assert_equal(result[1], [0, 3])
140
+ assert result[1].dtype.kind == 'i'
141
+ result = ndimage._measurements._select(
142
+ x, labels=labels, index=index, find_max=True,
143
+ find_max_positions=True)
144
+ assert len(result) == 2
145
+ xp_assert_equal(result[0], [1, 6])
146
+ xp_assert_equal(result[1], [1, 2])
147
+ assert result[1].dtype.kind == 'i'
148
+
149
+
150
+ @make_xp_test_case(ndimage.label)
151
+ def test_label01(xp):
152
+ data = xp.ones(())
153
+ out, n = ndimage.label(data)
154
+ assert out == 1
155
+ assert n == 1
156
+
157
+
158
+ @make_xp_test_case(ndimage.label)
159
+ def test_label02(xp):
160
+ data = xp.zeros(())
161
+ out, n = ndimage.label(data)
162
+ assert out == 0
163
+ assert n == 0
164
+
165
+
166
+ @make_xp_test_case(ndimage.label)
167
+ def test_label03(xp):
168
+ data = xp.ones([1])
169
+ out, n = ndimage.label(data)
170
+ assert_array_almost_equal(out, xp.asarray([1]))
171
+ assert n == 1
172
+
173
+
174
+ @make_xp_test_case(ndimage.label)
175
+ def test_label04(xp):
176
+ data = xp.zeros([1])
177
+ out, n = ndimage.label(data)
178
+ assert_array_almost_equal(out, xp.asarray([0]))
179
+ assert n == 0
180
+
181
+
182
+ @make_xp_test_case(ndimage.label)
183
+ def test_label05(xp):
184
+ data = xp.ones([5])
185
+ out, n = ndimage.label(data)
186
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1]))
187
+ assert n == 1
188
+
189
+
190
+ @make_xp_test_case(ndimage.label)
191
+ def test_label06(xp):
192
+ data = xp.asarray([1, 0, 1, 1, 0, 1])
193
+ out, n = ndimage.label(data)
194
+ assert_array_almost_equal(out, xp.asarray([1, 0, 2, 2, 0, 3]))
195
+ assert n == 3
196
+
197
+
198
+ @make_xp_test_case(ndimage.label)
199
+ def test_label07(xp):
200
+ data = xp.asarray([[0, 0, 0, 0, 0, 0],
201
+ [0, 0, 0, 0, 0, 0],
202
+ [0, 0, 0, 0, 0, 0],
203
+ [0, 0, 0, 0, 0, 0],
204
+ [0, 0, 0, 0, 0, 0],
205
+ [0, 0, 0, 0, 0, 0]])
206
+ out, n = ndimage.label(data)
207
+ assert_array_almost_equal(out, xp.asarray(
208
+ [[0, 0, 0, 0, 0, 0],
209
+ [0, 0, 0, 0, 0, 0],
210
+ [0, 0, 0, 0, 0, 0],
211
+ [0, 0, 0, 0, 0, 0],
212
+ [0, 0, 0, 0, 0, 0],
213
+ [0, 0, 0, 0, 0, 0]]))
214
+ assert n == 0
215
+
216
+
217
+ @make_xp_test_case(ndimage.label)
218
+ def test_label08(xp):
219
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
220
+ [0, 0, 1, 1, 0, 0],
221
+ [0, 0, 1, 1, 1, 0],
222
+ [1, 1, 0, 0, 0, 0],
223
+ [1, 1, 0, 0, 0, 0],
224
+ [0, 0, 0, 1, 1, 0]])
225
+ out, n = ndimage.label(data)
226
+ assert_array_almost_equal(out, xp.asarray([[1, 0, 0, 0, 0, 0],
227
+ [0, 0, 2, 2, 0, 0],
228
+ [0, 0, 2, 2, 2, 0],
229
+ [3, 3, 0, 0, 0, 0],
230
+ [3, 3, 0, 0, 0, 0],
231
+ [0, 0, 0, 4, 4, 0]]))
232
+ assert n == 4
233
+
234
+
235
+ @make_xp_test_case(ndimage.label)
236
+ def test_label09(xp):
237
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
238
+ [0, 0, 1, 1, 0, 0],
239
+ [0, 0, 1, 1, 1, 0],
240
+ [1, 1, 0, 0, 0, 0],
241
+ [1, 1, 0, 0, 0, 0],
242
+ [0, 0, 0, 1, 1, 0]])
243
+ struct = ndimage.generate_binary_structure(2, 2)
244
+ struct = xp.asarray(struct)
245
+ out, n = ndimage.label(data, struct)
246
+ assert_array_almost_equal(out, xp.asarray([[1, 0, 0, 0, 0, 0],
247
+ [0, 0, 2, 2, 0, 0],
248
+ [0, 0, 2, 2, 2, 0],
249
+ [2, 2, 0, 0, 0, 0],
250
+ [2, 2, 0, 0, 0, 0],
251
+ [0, 0, 0, 3, 3, 0]]))
252
+ assert n == 3
253
+
254
+
255
+ @make_xp_test_case(ndimage.label)
256
+ def test_label10(xp):
257
+ data = xp.asarray([[0, 0, 0, 0, 0, 0],
258
+ [0, 1, 1, 0, 1, 0],
259
+ [0, 1, 1, 1, 1, 0],
260
+ [0, 0, 0, 0, 0, 0]])
261
+ struct = ndimage.generate_binary_structure(2, 2)
262
+ struct = xp.asarray(struct)
263
+ out, n = ndimage.label(data, struct)
264
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0, 0, 0],
265
+ [0, 1, 1, 0, 1, 0],
266
+ [0, 1, 1, 1, 1, 0],
267
+ [0, 0, 0, 0, 0, 0]]))
268
+ assert n == 1
269
+
270
+
271
+ @make_xp_test_case(ndimage.label)
272
+ def test_label11(xp):
273
+ for type in types:
274
+ dtype = getattr(xp, type)
275
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
276
+ [0, 0, 1, 1, 0, 0],
277
+ [0, 0, 1, 1, 1, 0],
278
+ [1, 1, 0, 0, 0, 0],
279
+ [1, 1, 0, 0, 0, 0],
280
+ [0, 0, 0, 1, 1, 0]], dtype=dtype)
281
+ out, n = ndimage.label(data)
282
+ expected = [[1, 0, 0, 0, 0, 0],
283
+ [0, 0, 2, 2, 0, 0],
284
+ [0, 0, 2, 2, 2, 0],
285
+ [3, 3, 0, 0, 0, 0],
286
+ [3, 3, 0, 0, 0, 0],
287
+ [0, 0, 0, 4, 4, 0]]
288
+ expected = xp.asarray(expected)
289
+ assert_array_almost_equal(out, expected)
290
+ assert n == 4
291
+
292
+
293
+ @skip_xp_backends(np_only=True, reason='inplace output is numpy-specific')
294
+ @make_xp_test_case(ndimage.label)
295
+ def test_label11_inplace(xp):
296
+ for type in types:
297
+ dtype = getattr(xp, type)
298
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
299
+ [0, 0, 1, 1, 0, 0],
300
+ [0, 0, 1, 1, 1, 0],
301
+ [1, 1, 0, 0, 0, 0],
302
+ [1, 1, 0, 0, 0, 0],
303
+ [0, 0, 0, 1, 1, 0]], dtype=dtype)
304
+ n = ndimage.label(data, output=data)
305
+ expected = [[1, 0, 0, 0, 0, 0],
306
+ [0, 0, 2, 2, 0, 0],
307
+ [0, 0, 2, 2, 2, 0],
308
+ [3, 3, 0, 0, 0, 0],
309
+ [3, 3, 0, 0, 0, 0],
310
+ [0, 0, 0, 4, 4, 0]]
311
+ expected = xp.asarray(expected)
312
+ assert_array_almost_equal(data, expected)
313
+ assert n == 4
314
+
315
+
316
+ @make_xp_test_case(ndimage.label)
317
+ def test_label12(xp):
318
+ for type in types:
319
+ dtype = getattr(xp, type)
320
+ data = xp.asarray([[0, 0, 0, 0, 1, 1],
321
+ [0, 0, 0, 0, 0, 1],
322
+ [0, 0, 1, 0, 1, 1],
323
+ [0, 0, 1, 1, 1, 1],
324
+ [0, 0, 0, 1, 1, 0]], dtype=dtype)
325
+ out, n = ndimage.label(data)
326
+ expected = [[0, 0, 0, 0, 1, 1],
327
+ [0, 0, 0, 0, 0, 1],
328
+ [0, 0, 1, 0, 1, 1],
329
+ [0, 0, 1, 1, 1, 1],
330
+ [0, 0, 0, 1, 1, 0]]
331
+ expected = xp.asarray(expected)
332
+ assert_array_almost_equal(out, expected)
333
+ assert n == 1
334
+
335
+
336
+ @make_xp_test_case(ndimage.label)
337
+ def test_label13(xp):
338
+ for type in types:
339
+ dtype = getattr(xp, type)
340
+ data = xp.asarray([[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1],
341
+ [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
342
+ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
343
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]],
344
+ dtype=dtype)
345
+ out, n = ndimage.label(data)
346
+ expected = [[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1],
347
+ [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
348
+ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
349
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
350
+ expected = xp.asarray(expected)
351
+ assert_array_almost_equal(out, expected)
352
+ assert n == 1
353
+
354
+
355
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
356
+ reason='output=dtype is numpy-specific')
357
+ @make_xp_test_case(ndimage.label)
358
+ def test_label_output_typed(xp):
359
+ data = xp.ones([5])
360
+ for t in types:
361
+ dtype = getattr(xp, t)
362
+ output = xp.zeros([5], dtype=dtype)
363
+ n = ndimage.label(data, output=output)
364
+ assert_array_almost_equal(output,
365
+ xp.ones(output.shape, dtype=output.dtype))
366
+ assert n == 1
367
+
368
+
369
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
370
+ reason='output=dtype is numpy-specific')
371
+ @make_xp_test_case(ndimage.label)
372
+ def test_label_output_dtype(xp):
373
+ data = xp.ones([5])
374
+ for t in types:
375
+ dtype = getattr(xp, t)
376
+ output, n = ndimage.label(data, output=dtype)
377
+ assert_array_almost_equal(output,
378
+ xp.ones(output.shape, dtype=output.dtype))
379
+ assert output.dtype == t
380
+
381
+
382
+ @skip_xp_backends(np_only=True, reason="in-place output is numpy-specific")
383
+ @make_xp_test_case(ndimage.label)
384
+ def test_label_output_wrong_size(xp):
385
+ data = xp.ones([5])
386
+ for t in types:
387
+ dtype = getattr(xp, t)
388
+ output = xp.zeros([10], dtype=dtype)
389
+ assert_raises(ValueError, ndimage.label, data, output=output)
390
+
391
+
392
+ @make_xp_test_case(ndimage.label)
393
+ def test_label_structuring_elements(xp):
394
+ data = np.loadtxt(os.path.join(os.path.dirname(
395
+ __file__), "data", "label_inputs.txt"))
396
+ strels = np.loadtxt(os.path.join(
397
+ os.path.dirname(__file__), "data", "label_strels.txt"))
398
+ results = np.loadtxt(os.path.join(
399
+ os.path.dirname(__file__), "data", "label_results.txt"))
400
+ data = data.reshape((-1, 7, 7))
401
+ strels = strels.reshape((-1, 3, 3))
402
+ results = results.reshape((-1, 7, 7))
403
+
404
+ data = xp.asarray(data)
405
+ strels = xp.asarray(strels)
406
+ results = xp.asarray(results)
407
+ r = 0
408
+ for i in range(data.shape[0]):
409
+ d = data[i, :, :]
410
+ for j in range(strels.shape[0]):
411
+ s = strels[j, :, :]
412
+ xp_assert_equal(ndimage.label(d, s)[0], results[r, :, :], check_dtype=False)
413
+ r += 1
414
+
415
+
416
+ @make_xp_test_case(ndimage.label, ndimage.find_objects)
417
+ def test_ticket_742(xp):
418
+ def SE(img, thresh=.7, size=4):
419
+ mask = img > thresh
420
+ rank = len(mask.shape)
421
+ struct = ndimage.generate_binary_structure(rank, rank)
422
+ struct = xp.asarray(struct)
423
+ la, co = ndimage.label(mask,
424
+ struct)
425
+ _ = ndimage.find_objects(la)
426
+
427
+ if np.dtype(np.intp) != np.dtype('i'):
428
+ shape = (3, 1240, 1240)
429
+ a = np.random.rand(np.prod(shape)).reshape(shape)
430
+ a = xp.asarray(a)
431
+ # shouldn't crash
432
+ SE(a)
433
+
434
+
435
+ @make_xp_test_case(ndimage.label)
436
+ def test_gh_issue_3025(xp):
437
+ """Github issue #3025 - improper merging of labels"""
438
+ d = np.zeros((60, 320))
439
+ d[:, :257] = 1
440
+ d[:, 260:] = 1
441
+ d[36, 257] = 1
442
+ d[35, 258] = 1
443
+ d[35, 259] = 1
444
+ d = xp.asarray(d)
445
+ assert ndimage.label(d, xp.ones((3, 3)))[1] == 1
446
+
447
+
448
+ @make_xp_test_case(ndimage.label, ndimage.find_objects)
449
+ class TestFindObjects:
450
+ def test_label_default_dtype(self, xp):
451
+ test_array = np.random.rand(10, 10)
452
+ test_array = xp.asarray(test_array)
453
+ label, no_features = ndimage.label(test_array > 0.5)
454
+ assert label.dtype in (xp.int32, xp.int64)
455
+ # Shouldn't raise an exception
456
+ ndimage.find_objects(label)
457
+
458
+
459
+ def test_find_objects01(self, xp):
460
+ data = xp.ones([], dtype=xp.int64)
461
+ out = ndimage.find_objects(data)
462
+ assert out == [()]
463
+
464
+
465
+ def test_find_objects02(self, xp):
466
+ data = xp.zeros([], dtype=xp.int64)
467
+ out = ndimage.find_objects(data)
468
+ assert out == []
469
+
470
+
471
+ def test_find_objects03(self, xp):
472
+ data = xp.ones([1], dtype=xp.int64)
473
+ out = ndimage.find_objects(data)
474
+ assert out == [(slice(0, 1, None),)]
475
+
476
+
477
+ def test_find_objects04(self, xp):
478
+ data = xp.zeros([1], dtype=xp.int64)
479
+ out = ndimage.find_objects(data)
480
+ assert out == []
481
+
482
+
483
+ def test_find_objects05(self, xp):
484
+ data = xp.ones([5], dtype=xp.int64)
485
+ out = ndimage.find_objects(data)
486
+ assert out == [(slice(0, 5, None),)]
487
+
488
+
489
+ def test_find_objects06(self, xp):
490
+ data = xp.asarray([1, 0, 2, 2, 0, 3])
491
+ out = ndimage.find_objects(data)
492
+ assert out == [(slice(0, 1, None),),
493
+ (slice(2, 4, None),),
494
+ (slice(5, 6, None),)]
495
+
496
+
497
+ def test_find_objects07(self, xp):
498
+ data = xp.asarray([[0, 0, 0, 0, 0, 0],
499
+ [0, 0, 0, 0, 0, 0],
500
+ [0, 0, 0, 0, 0, 0],
501
+ [0, 0, 0, 0, 0, 0],
502
+ [0, 0, 0, 0, 0, 0],
503
+ [0, 0, 0, 0, 0, 0]])
504
+ out = ndimage.find_objects(data)
505
+ assert out == []
506
+
507
+
508
+ def test_find_objects08(self, xp):
509
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
510
+ [0, 0, 2, 2, 0, 0],
511
+ [0, 0, 2, 2, 2, 0],
512
+ [3, 3, 0, 0, 0, 0],
513
+ [3, 3, 0, 0, 0, 0],
514
+ [0, 0, 0, 4, 4, 0]])
515
+ out = ndimage.find_objects(data)
516
+ assert out == [(slice(0, 1, None), slice(0, 1, None)),
517
+ (slice(1, 3, None), slice(2, 5, None)),
518
+ (slice(3, 5, None), slice(0, 2, None)),
519
+ (slice(5, 6, None), slice(3, 5, None))]
520
+
521
+
522
+ def test_find_objects09(self, xp):
523
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
524
+ [0, 0, 2, 2, 0, 0],
525
+ [0, 0, 2, 2, 2, 0],
526
+ [0, 0, 0, 0, 0, 0],
527
+ [0, 0, 0, 0, 0, 0],
528
+ [0, 0, 0, 4, 4, 0]])
529
+ out = ndimage.find_objects(data)
530
+ assert out == [(slice(0, 1, None), slice(0, 1, None)),
531
+ (slice(1, 3, None), slice(2, 5, None)),
532
+ None,
533
+ (slice(5, 6, None), slice(3, 5, None))]
534
+
535
+
536
+ @make_xp_test_case(ndimage.value_indices)
537
+ def test_value_indices01(xp):
538
+ "Test dictionary keys and entries"
539
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
540
+ [0, 0, 2, 2, 0, 0],
541
+ [0, 0, 2, 2, 2, 0],
542
+ [0, 0, 0, 0, 0, 0],
543
+ [0, 0, 0, 0, 0, 0],
544
+ [0, 0, 0, 4, 4, 0]])
545
+ vi = ndimage.value_indices(data, ignore_value=0)
546
+ true_keys = [1, 2, 4]
547
+ assert list(vi.keys()) == true_keys
548
+
549
+ truevi = {k: xp.nonzero(data == k) for k in true_keys}
550
+
551
+ vi = ndimage.value_indices(data, ignore_value=0)
552
+ assert vi.keys() == truevi.keys()
553
+ for key in vi.keys():
554
+ assert len(vi[key]) == len(truevi[key])
555
+ for v, true_v in zip(vi[key], truevi[key]):
556
+ xp_assert_equal(v, true_v)
557
+
558
+
559
+ @make_xp_test_case(ndimage.value_indices)
560
+ def test_value_indices02(xp):
561
+ "Test input checking"
562
+ data = xp.zeros((5, 4), dtype=xp.float32)
563
+ msg = "Parameter 'arr' must be an integer array"
564
+ with assert_raises(ValueError, match=msg):
565
+ ndimage.value_indices(data)
566
+
567
+
568
+ @make_xp_test_case(ndimage.value_indices)
569
+ def test_value_indices03(xp):
570
+ "Test different input array shapes, from 1-D to 4-D"
571
+ for shape in [(36,), (18, 2), (3, 3, 4), (3, 3, 2, 2)]:
572
+ a = np.asarray((12*[1]+12*[2]+12*[3]), dtype=np.int32)
573
+ a = np.reshape(a, shape)
574
+
575
+ trueKeys = np.unique(a)
576
+ a = xp.asarray(a)
577
+ vi = ndimage.value_indices(a)
578
+ assert list(vi.keys()) == list(trueKeys)
579
+ for k in [int(x) for x in trueKeys]:
580
+ trueNdx = xp.nonzero(a == k)
581
+ assert len(vi[k]) == len(trueNdx)
582
+ for vik, true_vik in zip(vi[k], trueNdx):
583
+ xp_assert_equal(vik, true_vik)
584
+
585
+
586
+ @make_xp_test_case(ndimage.sum)
587
+ def test_sum01(xp):
588
+ for type in types:
589
+ dtype = getattr(xp, type)
590
+ input = xp.asarray([], dtype=dtype)
591
+ output = ndimage.sum(input)
592
+ assert output == 0
593
+
594
+
595
+ @make_xp_test_case(ndimage.sum)
596
+ def test_sum02(xp):
597
+ for type in types:
598
+ dtype = getattr(xp, type)
599
+ input = xp.zeros([0, 4], dtype=dtype)
600
+ output = ndimage.sum(input)
601
+ assert output == 0
602
+
603
+
604
+ @make_xp_test_case(ndimage.sum)
605
+ def test_sum03(xp):
606
+ for type in types:
607
+ dtype = getattr(xp, type)
608
+ input = xp.ones([], dtype=dtype)
609
+ output = ndimage.sum(input)
610
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
611
+
612
+
613
+ @make_xp_test_case(ndimage.sum)
614
+ def test_sum04(xp):
615
+ for type in types:
616
+ dtype = getattr(xp, type)
617
+ input = xp.asarray([1, 2], dtype=dtype)
618
+ output = ndimage.sum(input)
619
+ assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
620
+
621
+
622
+ @make_xp_test_case(ndimage.sum)
623
+ def test_sum05(xp):
624
+ for type in types:
625
+ dtype = getattr(xp, type)
626
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
627
+ output = ndimage.sum(input)
628
+ assert_almost_equal(output, xp.asarray(10.0), check_0d=False)
629
+
630
+
631
+ @make_xp_test_case(ndimage.sum)
632
+ def test_sum06(xp):
633
+ labels = np.asarray([], dtype=bool)
634
+ labels = xp.asarray(labels)
635
+ for type in types:
636
+ dtype = getattr(xp, type)
637
+ input = xp.asarray([], dtype=dtype)
638
+ output = ndimage.sum(input, labels=labels)
639
+ assert output == 0
640
+
641
+
642
+ @make_xp_test_case(ndimage.sum)
643
+ def test_sum07(xp):
644
+ labels = np.ones([0, 4], dtype=bool)
645
+ labels = xp.asarray(labels)
646
+ for type in types:
647
+ dtype = getattr(xp, type)
648
+ input = xp.zeros([0, 4], dtype=dtype)
649
+ output = ndimage.sum(input, labels=labels)
650
+ assert output == 0
651
+
652
+
653
+ @make_xp_test_case(ndimage.sum)
654
+ def test_sum08(xp):
655
+ labels = np.asarray([1, 0], dtype=bool)
656
+ labels = xp.asarray(labels)
657
+ for type in types:
658
+ dtype = getattr(xp, type)
659
+ input = xp.asarray([1, 2], dtype=dtype)
660
+ output = ndimage.sum(input, labels=labels)
661
+ assert output == 1
662
+
663
+
664
+ @make_xp_test_case(ndimage.sum)
665
+ def test_sum09(xp):
666
+ labels = np.asarray([1, 0], dtype=bool)
667
+ labels = xp.asarray(labels)
668
+ for type in types:
669
+ dtype = getattr(xp, type)
670
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
671
+ output = ndimage.sum(input, labels=labels)
672
+ assert_almost_equal(output, xp.asarray(4.0), check_0d=False)
673
+
674
+
675
+ @make_xp_test_case(ndimage.sum)
676
+ def test_sum10(xp):
677
+ labels = np.asarray([1, 0], dtype=bool)
678
+ input = np.asarray([[1, 2], [3, 4]], dtype=bool)
679
+
680
+ labels = xp.asarray(labels)
681
+ input = xp.asarray(input)
682
+ output = ndimage.sum(input, labels=labels)
683
+ assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
684
+
685
+
686
+ @make_xp_test_case(ndimage.sum)
687
+ def test_sum11(xp):
688
+ labels = xp.asarray([1, 2], dtype=xp.int8)
689
+ for type in types:
690
+ dtype = getattr(xp, type)
691
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
692
+ output = ndimage.sum(input, labels=labels,
693
+ index=2)
694
+ assert_almost_equal(output, xp.asarray(6.0), check_0d=False)
695
+
696
+
697
+ @make_xp_test_case(ndimage.sum)
698
+ def test_sum12(xp):
699
+ labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
700
+ for type in types:
701
+ dtype = getattr(xp, type)
702
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
703
+ output = ndimage.sum(input, labels=labels, index=xp.asarray([4, 8, 2]))
704
+ assert_array_almost_equal(output, xp.asarray([4.0, 0.0, 5.0]))
705
+
706
+
707
+ @make_xp_test_case(ndimage.sum)
708
+ def test_sum_labels(xp):
709
+ labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
710
+ for type in types:
711
+ dtype = getattr(xp, type)
712
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
713
+ output_sum = ndimage.sum(input, labels=labels, index=xp.asarray([4, 8, 2]))
714
+ output_labels = ndimage.sum_labels(
715
+ input, labels=labels, index=xp.asarray([4, 8, 2]))
716
+
717
+ assert xp.all(output_sum == output_labels)
718
+ assert_array_almost_equal(output_labels, xp.asarray([4.0, 0.0, 5.0]))
719
+
720
+
721
+ @make_xp_test_case(ndimage.mean)
722
+ def test_mean01(xp):
723
+ labels = np.asarray([1, 0], dtype=bool)
724
+ labels = xp.asarray(labels)
725
+ for type in types:
726
+ dtype = getattr(xp, type)
727
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
728
+ output = ndimage.mean(input, labels=labels)
729
+ assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
730
+
731
+
732
+ @make_xp_test_case(ndimage.mean)
733
+ def test_mean02(xp):
734
+ labels = np.asarray([1, 0], dtype=bool)
735
+ input = np.asarray([[1, 2], [3, 4]], dtype=bool)
736
+
737
+ labels = xp.asarray(labels)
738
+ input = xp.asarray(input)
739
+ output = ndimage.mean(input, labels=labels)
740
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
741
+
742
+
743
+ @make_xp_test_case(ndimage.mean)
744
+ def test_mean03(xp):
745
+ labels = xp.asarray([1, 2])
746
+ for type in types:
747
+ dtype = getattr(xp, type)
748
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
749
+ output = ndimage.mean(input, labels=labels,
750
+ index=2)
751
+ assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
752
+
753
+
754
+ @make_xp_test_case(ndimage.mean)
755
+ def test_mean04(xp):
756
+ labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
757
+ with np.errstate(all='ignore'):
758
+ for type in types:
759
+ dtype = getattr(xp, type)
760
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
761
+ output = ndimage.mean(input, labels=labels,
762
+ index=xp.asarray([4, 8, 2]))
763
+ # XXX: output[[0, 2]] does not work in array-api-strict; annoying
764
+ # assert_array_almost_equal(output[[0, 2]], xp.asarray([4.0, 2.5]))
765
+ assert output[0] == 4.0
766
+ assert output[2] == 2.5
767
+ assert xp.isnan(output[1])
768
+
769
+
770
+ @make_xp_test_case(ndimage.minimum)
771
+ def test_minimum01(xp):
772
+ labels = np.asarray([1, 0], dtype=bool)
773
+ labels = xp.asarray(labels)
774
+ for type in types:
775
+ dtype = getattr(xp, type)
776
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
777
+ output = ndimage.minimum(input, labels=labels)
778
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
779
+
780
+
781
+ @make_xp_test_case(ndimage.minimum)
782
+ def test_minimum02(xp):
783
+ labels = np.asarray([1, 0], dtype=bool)
784
+ input = np.asarray([[2, 2], [2, 4]], dtype=bool)
785
+
786
+ labels = xp.asarray(labels)
787
+ input = xp.asarray(input)
788
+ output = ndimage.minimum(input, labels=labels)
789
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
790
+
791
+
792
+ @make_xp_test_case(ndimage.minimum)
793
+ def test_minimum03(xp):
794
+ labels = xp.asarray([1, 2])
795
+ for type in types:
796
+ dtype = getattr(xp, type)
797
+
798
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
799
+ output = ndimage.minimum(input, labels=labels,
800
+ index=2)
801
+ assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
802
+
803
+
804
+ @make_xp_test_case(ndimage.minimum)
805
+ def test_minimum04(xp):
806
+ labels = xp.asarray([[1, 2], [2, 3]])
807
+ for type in types:
808
+ dtype = getattr(xp, type)
809
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
810
+ output = ndimage.minimum(input, labels=labels,
811
+ index=xp.asarray([2, 3, 8]))
812
+ assert_array_almost_equal(output, xp.asarray([2.0, 4.0, 0.0]))
813
+
814
+
815
+ @make_xp_test_case(ndimage.maximum)
816
+ def test_maximum01(xp):
817
+ labels = np.asarray([1, 0], dtype=bool)
818
+ labels = xp.asarray(labels)
819
+ for type in types:
820
+ dtype = getattr(xp, type)
821
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
822
+ output = ndimage.maximum(input, labels=labels)
823
+ assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
824
+
825
+
826
+ @make_xp_test_case(ndimage.maximum)
827
+ def test_maximum02(xp):
828
+ labels = np.asarray([1, 0], dtype=bool)
829
+ input = np.asarray([[2, 2], [2, 4]], dtype=bool)
830
+ labels = xp.asarray(labels)
831
+ input = xp.asarray(input)
832
+ output = ndimage.maximum(input, labels=labels)
833
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
834
+
835
+
836
+ @make_xp_test_case(ndimage.maximum)
837
+ def test_maximum03(xp):
838
+ labels = xp.asarray([1, 2])
839
+ for type in types:
840
+ dtype = getattr(xp, type)
841
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
842
+ output = ndimage.maximum(input, labels=labels,
843
+ index=2)
844
+ assert_almost_equal(output, xp.asarray(4.0), check_0d=False)
845
+
846
+
847
+ @make_xp_test_case(ndimage.maximum)
848
+ def test_maximum04(xp):
849
+ labels = xp.asarray([[1, 2], [2, 3]])
850
+ for type in types:
851
+ dtype = getattr(xp, type)
852
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
853
+ output = ndimage.maximum(input, labels=labels,
854
+ index=xp.asarray([2, 3, 8]))
855
+ assert_array_almost_equal(output, xp.asarray([3.0, 4.0, 0.0]))
856
+
857
+
858
+ @make_xp_test_case(ndimage.maximum)
859
+ def test_maximum05(xp):
860
+ # Regression test for ticket #501 (Trac)
861
+ x = xp.asarray([-3, -2, -1])
862
+ assert ndimage.maximum(x) == -1
863
+
864
+
865
+ @make_xp_test_case(ndimage.median)
866
+ def test_median01(xp):
867
+ a = xp.asarray([[1, 2, 0, 1],
868
+ [5, 3, 0, 4],
869
+ [0, 0, 0, 7],
870
+ [9, 3, 0, 0]])
871
+ labels = xp.asarray([[1, 1, 0, 2],
872
+ [1, 1, 0, 2],
873
+ [0, 0, 0, 2],
874
+ [3, 3, 0, 0]])
875
+ output = ndimage.median(a, labels=labels, index=xp.asarray([1, 2, 3]))
876
+ assert_array_almost_equal(output, xp.asarray([2.5, 4.0, 6.0]))
877
+
878
+
879
+ @make_xp_test_case(ndimage.median)
880
+ def test_median02(xp):
881
+ a = xp.asarray([[1, 2, 0, 1],
882
+ [5, 3, 0, 4],
883
+ [0, 0, 0, 7],
884
+ [9, 3, 0, 0]])
885
+ output = ndimage.median(a)
886
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
887
+
888
+
889
+ @make_xp_test_case(ndimage.median)
890
+ def test_median03(xp):
891
+ a = xp.asarray([[1, 2, 0, 1],
892
+ [5, 3, 0, 4],
893
+ [0, 0, 0, 7],
894
+ [9, 3, 0, 0]])
895
+ labels = xp.asarray([[1, 1, 0, 2],
896
+ [1, 1, 0, 2],
897
+ [0, 0, 0, 2],
898
+ [3, 3, 0, 0]])
899
+ output = ndimage.median(a, labels=labels)
900
+ assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
901
+
902
+
903
+ @make_xp_test_case(ndimage.median)
904
+ def test_median_gh12836_bool(xp):
905
+ # test boolean addition fix on example from gh-12836
906
+ a = np.asarray([1, 1], dtype=bool)
907
+ a = xp.asarray(a)
908
+ output = ndimage.median(a, labels=xp.ones((2,)), index=xp.asarray([1]))
909
+ assert_array_almost_equal(output, xp.asarray([1.0]))
910
+
911
+
912
+ @make_xp_test_case(ndimage.median)
913
+ def test_median_no_int_overflow(xp):
914
+ # test integer overflow fix on example from gh-12836
915
+ a = xp.asarray([65, 70], dtype=xp.int8)
916
+ output = ndimage.median(a, labels=xp.ones((2,)), index=xp.asarray([1]))
917
+ assert_array_almost_equal(output, xp.asarray([67.5]))
918
+
919
+
920
+ @make_xp_test_case(ndimage.variance)
921
+ def test_variance01(xp):
922
+ with np.errstate(all='ignore'):
923
+ for type in types:
924
+ dtype = getattr(xp, type)
925
+ input = xp.asarray([], dtype=dtype)
926
+ with warnings.catch_warnings():
927
+ warnings.filterwarnings("ignore", "Mean of empty slice", RuntimeWarning)
928
+ output = ndimage.variance(input)
929
+ assert xp.isnan(output)
930
+
931
+
932
+ @make_xp_test_case(ndimage.variance)
933
+ def test_variance02(xp):
934
+ for type in types:
935
+ dtype = getattr(xp, type)
936
+ input = xp.asarray([1], dtype=dtype)
937
+ output = ndimage.variance(input)
938
+ assert_almost_equal(output, xp.asarray(0.0), check_0d=False)
939
+
940
+
941
+ @make_xp_test_case(ndimage.variance)
942
+ def test_variance03(xp):
943
+ for type in types:
944
+ dtype = getattr(xp, type)
945
+ input = xp.asarray([1, 3], dtype=dtype)
946
+ output = ndimage.variance(input)
947
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
948
+
949
+
950
+ @make_xp_test_case(ndimage.variance)
951
+ def test_variance04(xp):
952
+ input = np.asarray([1, 0], dtype=bool)
953
+ input = xp.asarray(input)
954
+ output = ndimage.variance(input)
955
+ assert_almost_equal(output, xp.asarray(0.25), check_0d=False)
956
+
957
+
958
+ @make_xp_test_case(ndimage.variance)
959
+ def test_variance05(xp):
960
+ labels = xp.asarray([2, 2, 3])
961
+ for type in types:
962
+ dtype = getattr(xp, type)
963
+
964
+ input = xp.asarray([1, 3, 8], dtype=dtype)
965
+ output = ndimage.variance(input, labels, 2)
966
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
967
+
968
+
969
+ @make_xp_test_case(ndimage.variance)
970
+ def test_variance06(xp):
971
+ labels = xp.asarray([2, 2, 3, 3, 4])
972
+ with np.errstate(all='ignore'):
973
+ for type in types:
974
+ dtype = getattr(xp, type)
975
+ input = xp.asarray([1, 3, 8, 10, 8], dtype=dtype)
976
+ output = ndimage.variance(input, labels, xp.asarray([2, 3, 4]))
977
+ assert_array_almost_equal(output, xp.asarray([1.0, 1.0, 0.0]))
978
+
979
+
980
+ @make_xp_test_case(ndimage.standard_deviation)
981
+ def test_standard_deviation01(xp):
982
+ with np.errstate(all='ignore'):
983
+ for type in types:
984
+ dtype = getattr(xp, type)
985
+ input = xp.asarray([], dtype=dtype)
986
+ with warnings.catch_warnings():
987
+ warnings.filterwarnings("ignore", "Mean of empty slice", RuntimeWarning)
988
+ output = ndimage.standard_deviation(input)
989
+ assert xp.isnan(output)
990
+
991
+
992
+ @make_xp_test_case(ndimage.standard_deviation)
993
+ def test_standard_deviation02(xp):
994
+ for type in types:
995
+ dtype = getattr(xp, type)
996
+ input = xp.asarray([1], dtype=dtype)
997
+ output = ndimage.standard_deviation(input)
998
+ assert_almost_equal(output, xp.asarray(0.0), check_0d=False)
999
+
1000
+
1001
+ @make_xp_test_case(ndimage.standard_deviation)
1002
+ def test_standard_deviation03(xp):
1003
+ for type in types:
1004
+ dtype = getattr(xp, type)
1005
+ input = xp.asarray([1, 3], dtype=dtype)
1006
+ output = ndimage.standard_deviation(input)
1007
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
1008
+
1009
+
1010
+ @make_xp_test_case(ndimage.standard_deviation)
1011
+ def test_standard_deviation04(xp):
1012
+ input = np.asarray([1, 0], dtype=bool)
1013
+ input = xp.asarray(input)
1014
+ output = ndimage.standard_deviation(input)
1015
+ assert_almost_equal(output, xp.asarray(0.5), check_0d=False)
1016
+
1017
+
1018
+ @make_xp_test_case(ndimage.standard_deviation)
1019
+ def test_standard_deviation05(xp):
1020
+ labels = xp.asarray([2, 2, 3])
1021
+ for type in types:
1022
+ dtype = getattr(xp, type)
1023
+ input = xp.asarray([1, 3, 8], dtype=dtype)
1024
+ output = ndimage.standard_deviation(input, labels, 2)
1025
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
1026
+
1027
+
1028
+ @make_xp_test_case(ndimage.standard_deviation)
1029
+ def test_standard_deviation06(xp):
1030
+ labels = xp.asarray([2, 2, 3, 3, 4])
1031
+ with np.errstate(all='ignore'):
1032
+ for type in types:
1033
+ dtype = getattr(xp, type)
1034
+ input = xp.asarray([1, 3, 8, 10, 8], dtype=dtype)
1035
+ output = ndimage.standard_deviation(
1036
+ input, labels, xp.asarray([2, 3, 4])
1037
+ )
1038
+ assert_array_almost_equal(output, xp.asarray([1.0, 1.0, 0.0]))
1039
+
1040
+
1041
+ @make_xp_test_case(ndimage.standard_deviation)
1042
+ def test_standard_deviation07(xp):
1043
+ labels = xp.asarray([1])
1044
+ with np.errstate(all='ignore'):
1045
+ for type in types:
1046
+ if is_torch(xp) and type == 'uint8':
1047
+ pytest.xfail("value cannot be converted to type uint8 "
1048
+ "without overflow")
1049
+ dtype = getattr(xp, type)
1050
+ input = xp.asarray([-0.00619519], dtype=dtype)
1051
+ output = ndimage.standard_deviation(input, labels, xp.asarray([1]))
1052
+ assert_array_almost_equal(output, xp.asarray([0]))
1053
+
1054
+
1055
+ @make_xp_test_case(ndimage.minimum_position)
1056
+ def test_minimum_position01(xp):
1057
+ labels = np.asarray([1, 0], dtype=bool)
1058
+ labels = xp.asarray(labels)
1059
+ for type in types:
1060
+ dtype = getattr(xp, type)
1061
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
1062
+ output = ndimage.minimum_position(input, labels=labels)
1063
+ assert output == (0, 0)
1064
+
1065
+
1066
+ @make_xp_test_case(ndimage.minimum_position)
1067
+ def test_minimum_position02(xp):
1068
+ for type in types:
1069
+ dtype = getattr(xp, type)
1070
+ input = xp.asarray([[5, 4, 2, 5],
1071
+ [3, 7, 0, 2],
1072
+ [1, 5, 1, 1]], dtype=dtype)
1073
+ output = ndimage.minimum_position(input)
1074
+ assert output == (1, 2)
1075
+
1076
+
1077
+ @make_xp_test_case(ndimage.minimum_position)
1078
+ def test_minimum_position03(xp):
1079
+ input = np.asarray([[5, 4, 2, 5],
1080
+ [3, 7, 0, 2],
1081
+ [1, 5, 1, 1]], dtype=bool)
1082
+ input = xp.asarray(input)
1083
+ output = ndimage.minimum_position(input)
1084
+ assert output == (1, 2)
1085
+
1086
+
1087
+ @make_xp_test_case(ndimage.minimum_position)
1088
+ def test_minimum_position04(xp):
1089
+ input = np.asarray([[5, 4, 2, 5],
1090
+ [3, 7, 1, 2],
1091
+ [1, 5, 1, 1]], dtype=bool)
1092
+ input = xp.asarray(input)
1093
+ output = ndimage.minimum_position(input)
1094
+ assert output == (0, 0)
1095
+
1096
+
1097
+ @make_xp_test_case(ndimage.minimum_position)
1098
+ def test_minimum_position05(xp):
1099
+ labels = xp.asarray([1, 2, 0, 4])
1100
+ for type in types:
1101
+ dtype = getattr(xp, type)
1102
+ input = xp.asarray([[5, 4, 2, 5],
1103
+ [3, 7, 0, 2],
1104
+ [1, 5, 2, 3]], dtype=dtype)
1105
+ output = ndimage.minimum_position(input, labels)
1106
+ assert output == (2, 0)
1107
+
1108
+
1109
+ @make_xp_test_case(ndimage.minimum_position)
1110
+ def test_minimum_position06(xp):
1111
+ labels = xp.asarray([1, 2, 3, 4])
1112
+ for type in types:
1113
+ dtype = getattr(xp, type)
1114
+ input = xp.asarray([[5, 4, 2, 5],
1115
+ [3, 7, 0, 2],
1116
+ [1, 5, 1, 1]], dtype=dtype)
1117
+ output = ndimage.minimum_position(input, labels, 2)
1118
+ assert output == (0, 1)
1119
+
1120
+
1121
+ @make_xp_test_case(ndimage.minimum_position)
1122
+ def test_minimum_position07(xp):
1123
+ labels = xp.asarray([1, 2, 3, 4])
1124
+ for type in types:
1125
+ dtype = getattr(xp, type)
1126
+ input = xp.asarray([[5, 4, 2, 5],
1127
+ [3, 7, 0, 2],
1128
+ [1, 5, 1, 1]], dtype=dtype)
1129
+ output = ndimage.minimum_position(input, labels,
1130
+ xp.asarray([2, 3]))
1131
+ assert output[0] == (0, 1)
1132
+ assert output[1] == (1, 2)
1133
+
1134
+
1135
+ @make_xp_test_case(ndimage.maximum_position)
1136
+ def test_maximum_position01(xp):
1137
+ labels = np.asarray([1, 0], dtype=bool)
1138
+ labels = xp.asarray(labels)
1139
+ for type in types:
1140
+ dtype = getattr(xp, type)
1141
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
1142
+ output = ndimage.maximum_position(input,
1143
+ labels=labels)
1144
+ assert output == (1, 0)
1145
+
1146
+
1147
+ @make_xp_test_case(ndimage.maximum_position)
1148
+ def test_maximum_position02(xp):
1149
+ for type in types:
1150
+ dtype = getattr(xp, type)
1151
+ input = xp.asarray([[5, 4, 2, 5],
1152
+ [3, 7, 8, 2],
1153
+ [1, 5, 1, 1]], dtype=dtype)
1154
+ output = ndimage.maximum_position(input)
1155
+ assert output == (1, 2)
1156
+
1157
+
1158
+ @make_xp_test_case(ndimage.maximum_position)
1159
+ def test_maximum_position03(xp):
1160
+ input = np.asarray([[5, 4, 2, 5],
1161
+ [3, 7, 8, 2],
1162
+ [1, 5, 1, 1]], dtype=bool)
1163
+ input = xp.asarray(input)
1164
+ output = ndimage.maximum_position(input)
1165
+ assert output == (0, 0)
1166
+
1167
+
1168
+ @make_xp_test_case(ndimage.maximum_position)
1169
+ def test_maximum_position04(xp):
1170
+ labels = xp.asarray([1, 2, 0, 4])
1171
+ for type in types:
1172
+ dtype = getattr(xp, type)
1173
+ input = xp.asarray([[5, 4, 2, 5],
1174
+ [3, 7, 8, 2],
1175
+ [1, 5, 1, 1]], dtype=dtype)
1176
+ output = ndimage.maximum_position(input, labels)
1177
+ assert output == (1, 1)
1178
+
1179
+
1180
+ @make_xp_test_case(ndimage.maximum_position)
1181
+ def test_maximum_position05(xp):
1182
+ labels = xp.asarray([1, 2, 0, 4])
1183
+ for type in types:
1184
+ dtype = getattr(xp, type)
1185
+ input = xp.asarray([[5, 4, 2, 5],
1186
+ [3, 7, 8, 2],
1187
+ [1, 5, 1, 1]], dtype=dtype)
1188
+ output = ndimage.maximum_position(input, labels, 1)
1189
+ assert output == (0, 0)
1190
+
1191
+
1192
+ @make_xp_test_case(ndimage.maximum_position)
1193
+ def test_maximum_position06(xp):
1194
+ labels = xp.asarray([1, 2, 0, 4])
1195
+ for type in types:
1196
+ dtype = getattr(xp, type)
1197
+ input = xp.asarray([[5, 4, 2, 5],
1198
+ [3, 7, 8, 2],
1199
+ [1, 5, 1, 1]], dtype=dtype)
1200
+ output = ndimage.maximum_position(input, labels,
1201
+ xp.asarray([1, 2]))
1202
+ assert output[0] == (0, 0)
1203
+ assert output[1] == (1, 1)
1204
+
1205
+
1206
+ @make_xp_test_case(ndimage.maximum_position)
1207
+ def test_maximum_position07(xp):
1208
+ # Test float labels
1209
+ labels = xp.asarray([1.0, 2.5, 0.0, 4.5])
1210
+ for type in types:
1211
+ dtype = getattr(xp, type)
1212
+ input = xp.asarray([[5, 4, 2, 5],
1213
+ [3, 7, 8, 2],
1214
+ [1, 5, 1, 1]], dtype=dtype)
1215
+ output = ndimage.maximum_position(input, labels,
1216
+ xp.asarray([1.0, 4.5]))
1217
+ assert output[0] == (0, 0)
1218
+ assert output[1] == (0, 3)
1219
+
1220
+
1221
+ @make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum,
1222
+ ndimage.minimum_position, ndimage.maximum_position)
1223
+ def test_extrema01(xp):
1224
+ labels = np.asarray([1, 0], dtype=bool)
1225
+ labels = xp.asarray(labels)
1226
+ for type in types:
1227
+ dtype = getattr(xp, type)
1228
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
1229
+ output1 = ndimage.extrema(input, labels=labels)
1230
+ output2 = ndimage.minimum(input, labels=labels)
1231
+ output3 = ndimage.maximum(input, labels=labels)
1232
+ output4 = ndimage.minimum_position(input,
1233
+ labels=labels)
1234
+ output5 = ndimage.maximum_position(input,
1235
+ labels=labels)
1236
+ assert output1 == (output2, output3, output4, output5)
1237
+
1238
+
1239
+ @make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum,
1240
+ ndimage.minimum_position, ndimage.maximum_position)
1241
+ def test_extrema02(xp):
1242
+ labels = xp.asarray([1, 2])
1243
+ for type in types:
1244
+ dtype = getattr(xp, type)
1245
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
1246
+ output1 = ndimage.extrema(input, labels=labels,
1247
+ index=2)
1248
+ output2 = ndimage.minimum(input, labels=labels,
1249
+ index=2)
1250
+ output3 = ndimage.maximum(input, labels=labels,
1251
+ index=2)
1252
+ output4 = ndimage.minimum_position(input,
1253
+ labels=labels, index=2)
1254
+ output5 = ndimage.maximum_position(input,
1255
+ labels=labels, index=2)
1256
+ assert output1 == (output2, output3, output4, output5)
1257
+
1258
+
1259
+ @make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum,
1260
+ ndimage.minimum_position, ndimage.maximum_position)
1261
+ def test_extrema03(xp):
1262
+ labels = xp.asarray([[1, 2], [2, 3]])
1263
+ for type in types:
1264
+ if is_torch(xp) and type in ("uint16", "uint32", "uint64"):
1265
+ pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
1266
+
1267
+ dtype = getattr(xp, type)
1268
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
1269
+ output1 = ndimage.extrema(input,
1270
+ labels=labels,
1271
+ index=xp.asarray([2, 3, 8]))
1272
+ output2 = ndimage.minimum(input,
1273
+ labels=labels,
1274
+ index=xp.asarray([2, 3, 8]))
1275
+ output3 = ndimage.maximum(input, labels=labels,
1276
+ index=xp.asarray([2, 3, 8]))
1277
+ output4 = ndimage.minimum_position(input,
1278
+ labels=labels,
1279
+ index=xp.asarray([2, 3, 8]))
1280
+ output5 = ndimage.maximum_position(input,
1281
+ labels=labels,
1282
+ index=xp.asarray([2, 3, 8]))
1283
+ assert_array_almost_equal(output1[0], output2)
1284
+ assert_array_almost_equal(output1[1], output3)
1285
+ assert output1[2] == output4
1286
+ assert output1[3] == output5
1287
+
1288
+
1289
+ @make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum,
1290
+ ndimage.minimum_position, ndimage.maximum_position)
1291
+ def test_extrema04(xp):
1292
+ labels = xp.asarray([1, 2, 0, 4])
1293
+ for type in types:
1294
+ if is_torch(xp) and type in ("uint16", "uint32", "uint64"):
1295
+ pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
1296
+
1297
+ dtype = getattr(xp, type)
1298
+ input = xp.asarray([[5, 4, 2, 5],
1299
+ [3, 7, 8, 2],
1300
+ [1, 5, 1, 1]], dtype=dtype)
1301
+ output1 = ndimage.extrema(input, labels, xp.asarray([1, 2]))
1302
+ output2 = ndimage.minimum(input, labels, xp.asarray([1, 2]))
1303
+ output3 = ndimage.maximum(input, labels, xp.asarray([1, 2]))
1304
+ output4 = ndimage.minimum_position(input, labels,
1305
+ xp.asarray([1, 2]))
1306
+ output5 = ndimage.maximum_position(input, labels,
1307
+ xp.asarray([1, 2]))
1308
+ assert_array_almost_equal(output1[0], output2)
1309
+ assert_array_almost_equal(output1[1], output3)
1310
+ assert output1[2] == output4
1311
+ assert output1[3] == output5
1312
+
1313
+
1314
+ @make_xp_test_case(ndimage.center_of_mass)
1315
+ def test_center_of_mass01(xp):
1316
+ expected = (0.0, 0.0)
1317
+ for type in types:
1318
+ dtype = getattr(xp, type)
1319
+ input = xp.asarray([[1, 0], [0, 0]], dtype=dtype)
1320
+ output = ndimage.center_of_mass(input)
1321
+ assert output == expected
1322
+
1323
+
1324
+ @make_xp_test_case(ndimage.center_of_mass)
1325
+ def test_center_of_mass02(xp):
1326
+ expected = (1, 0)
1327
+ for type in types:
1328
+ dtype = getattr(xp, type)
1329
+ input = xp.asarray([[0, 0], [1, 0]], dtype=dtype)
1330
+ output = ndimage.center_of_mass(input)
1331
+ assert output == expected
1332
+
1333
+
1334
+ @make_xp_test_case(ndimage.center_of_mass)
1335
+ def test_center_of_mass03(xp):
1336
+ expected = (0, 1)
1337
+ for type in types:
1338
+ dtype = getattr(xp, type)
1339
+ input = xp.asarray([[0, 1], [0, 0]], dtype=dtype)
1340
+ output = ndimage.center_of_mass(input)
1341
+ assert output == expected
1342
+
1343
+
1344
+ @make_xp_test_case(ndimage.center_of_mass)
1345
+ def test_center_of_mass04(xp):
1346
+ expected = (1, 1)
1347
+ for type in types:
1348
+ dtype = getattr(xp, type)
1349
+ input = xp.asarray([[0, 0], [0, 1]], dtype=dtype)
1350
+ output = ndimage.center_of_mass(input)
1351
+ assert output == expected
1352
+
1353
+
1354
+ @make_xp_test_case(ndimage.center_of_mass)
1355
+ def test_center_of_mass05(xp):
1356
+ expected = (0.5, 0.5)
1357
+ for type in types:
1358
+ dtype = getattr(xp, type)
1359
+ input = xp.asarray([[1, 1], [1, 1]], dtype=dtype)
1360
+ output = ndimage.center_of_mass(input)
1361
+ assert output == expected
1362
+
1363
+
1364
+ @make_xp_test_case(ndimage.center_of_mass)
1365
+ def test_center_of_mass06(xp):
1366
+ expected = (0.5, 0.5)
1367
+ input = np.asarray([[1, 2], [3, 1]], dtype=bool)
1368
+ input = xp.asarray(input)
1369
+ output = ndimage.center_of_mass(input)
1370
+ assert output == expected
1371
+
1372
+
1373
+ @make_xp_test_case(ndimage.center_of_mass)
1374
+ def test_center_of_mass07(xp):
1375
+ labels = xp.asarray([1, 0])
1376
+ expected = (0.5, 0.0)
1377
+ input = np.asarray([[1, 2], [3, 1]], dtype=bool)
1378
+ input = xp.asarray(input)
1379
+ output = ndimage.center_of_mass(input, labels)
1380
+ assert output == expected
1381
+
1382
+
1383
+ @make_xp_test_case(ndimage.center_of_mass)
1384
+ def test_center_of_mass08(xp):
1385
+ labels = xp.asarray([1, 2])
1386
+ expected = (0.5, 1.0)
1387
+ input = np.asarray([[5, 2], [3, 1]], dtype=bool)
1388
+ input = xp.asarray(input)
1389
+ output = ndimage.center_of_mass(input, labels, 2)
1390
+ assert output == expected
1391
+
1392
+
1393
+ @make_xp_test_case(ndimage.center_of_mass)
1394
+ def test_center_of_mass09(xp):
1395
+ labels = xp.asarray((1, 2))
1396
+ expected = xp.asarray([(0.5, 0.0), (0.5, 1.0)], dtype=xp.float64)
1397
+ input = np.asarray([[1, 2], [1, 1]], dtype=bool)
1398
+ input = xp.asarray(input)
1399
+ output = ndimage.center_of_mass(input, labels, xp.asarray([1, 2]))
1400
+ xp_assert_equal(xp.asarray(output), xp.asarray(expected))
1401
+
1402
+
1403
+ @make_xp_test_case(ndimage.histogram)
1404
+ def test_histogram01(xp):
1405
+ expected = xp.ones(10)
1406
+ input = xp.arange(10)
1407
+ output = ndimage.histogram(input, 0, 10, 10)
1408
+ assert_array_almost_equal(output, expected)
1409
+
1410
+
1411
+ @make_xp_test_case(ndimage.histogram)
1412
+ def test_histogram02(xp):
1413
+ labels = xp.asarray([1, 1, 1, 1, 2, 2, 2, 2])
1414
+ expected = xp.asarray([0, 2, 0, 1, 1])
1415
+ input = xp.asarray([1, 1, 3, 4, 3, 3, 3, 3])
1416
+ output = ndimage.histogram(input, 0, 4, 5, labels, 1)
1417
+ assert_array_almost_equal(output, expected)
1418
+
1419
+
1420
+ @skip_xp_backends(np_only=True, reason='object arrays')
1421
+ @make_xp_test_case(ndimage.histogram)
1422
+ def test_histogram03(xp):
1423
+ labels = xp.asarray([1, 0, 1, 1, 2, 2, 2, 2])
1424
+ expected1 = xp.asarray([0, 1, 0, 1, 1])
1425
+ expected2 = xp.asarray([0, 0, 0, 3, 0])
1426
+ input = xp.asarray([1, 1, 3, 4, 3, 5, 3, 3])
1427
+
1428
+ output = ndimage.histogram(input, 0, 4, 5, labels, (1, 2))
1429
+
1430
+ assert_array_almost_equal(output[0], expected1)
1431
+ assert_array_almost_equal(output[1], expected2)
1432
+
1433
+ @make_xp_test_case(ndimage.mean, ndimage.variance, ndimage.standard_deviation,
1434
+ ndimage.median, ndimage.minimum, ndimage.maximum)
1435
+ def test_stat_funcs_2d(xp):
1436
+ a = xp.asarray([[5, 6, 0, 0, 0], [8, 9, 0, 0, 0], [0, 0, 0, 3, 5]])
1437
+ lbl = xp.asarray([[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 2, 2]])
1438
+
1439
+ mean = ndimage.mean(a, labels=lbl, index=xp.asarray([1, 2]))
1440
+ xp_assert_equal(mean, xp.asarray([7.0, 4.0], dtype=xp.float64))
1441
+
1442
+ var = ndimage.variance(a, labels=lbl, index=xp.asarray([1, 2]))
1443
+ xp_assert_equal(var, xp.asarray([2.5, 1.0], dtype=xp.float64))
1444
+
1445
+ std = ndimage.standard_deviation(a, labels=lbl, index=xp.asarray([1, 2]))
1446
+ assert_array_almost_equal(std, xp.sqrt(xp.asarray([2.5, 1.0], dtype=xp.float64)))
1447
+
1448
+ med = ndimage.median(a, labels=lbl, index=xp.asarray([1, 2]))
1449
+ xp_assert_equal(med, xp.asarray([7.0, 4.0], dtype=xp.float64))
1450
+
1451
+ min = ndimage.minimum(a, labels=lbl, index=xp.asarray([1, 2]))
1452
+ xp_assert_equal(min, xp.asarray([5, 3]), check_dtype=False)
1453
+
1454
+ max = ndimage.maximum(a, labels=lbl, index=xp.asarray([1, 2]))
1455
+ xp_assert_equal(max, xp.asarray([9, 5]), check_dtype=False)
1456
+
1457
+
1458
+ @skip_xp_backends("cupy", reason="no watershed_ift on CuPy")
1459
+ @make_xp_test_case(ndimage.watershed_ift)
1460
+ class TestWatershedIft:
1461
+
1462
+ def test_watershed_ift01(self, xp):
1463
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
1464
+ [0, 1, 1, 1, 1, 1, 0],
1465
+ [0, 1, 0, 0, 0, 1, 0],
1466
+ [0, 1, 0, 0, 0, 1, 0],
1467
+ [0, 1, 0, 0, 0, 1, 0],
1468
+ [0, 1, 1, 1, 1, 1, 0],
1469
+ [0, 0, 0, 0, 0, 0, 0],
1470
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
1471
+ markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
1472
+ [0, 0, 0, 0, 0, 0, 0],
1473
+ [0, 0, 0, 0, 0, 0, 0],
1474
+ [0, 0, 0, 1, 0, 0, 0],
1475
+ [0, 0, 0, 0, 0, 0, 0],
1476
+ [0, 0, 0, 0, 0, 0, 0],
1477
+ [0, 0, 0, 0, 0, 0, 0],
1478
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
1479
+ structure=xp.asarray([[1, 1, 1],
1480
+ [1, 1, 1],
1481
+ [1, 1, 1]])
1482
+ out = ndimage.watershed_ift(data, markers, structure=structure)
1483
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
1484
+ [-1, 1, 1, 1, 1, 1, -1],
1485
+ [-1, 1, 1, 1, 1, 1, -1],
1486
+ [-1, 1, 1, 1, 1, 1, -1],
1487
+ [-1, 1, 1, 1, 1, 1, -1],
1488
+ [-1, 1, 1, 1, 1, 1, -1],
1489
+ [-1, -1, -1, -1, -1, -1, -1],
1490
+ [-1, -1, -1, -1, -1, -1, -1]]
1491
+ assert_array_almost_equal(out, xp.asarray(expected))
1492
+
1493
+ def test_watershed_ift02(self, xp):
1494
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
1495
+ [0, 1, 1, 1, 1, 1, 0],
1496
+ [0, 1, 0, 0, 0, 1, 0],
1497
+ [0, 1, 0, 0, 0, 1, 0],
1498
+ [0, 1, 0, 0, 0, 1, 0],
1499
+ [0, 1, 1, 1, 1, 1, 0],
1500
+ [0, 0, 0, 0, 0, 0, 0],
1501
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
1502
+ markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
1503
+ [0, 0, 0, 0, 0, 0, 0],
1504
+ [0, 0, 0, 0, 0, 0, 0],
1505
+ [0, 0, 0, 1, 0, 0, 0],
1506
+ [0, 0, 0, 0, 0, 0, 0],
1507
+ [0, 0, 0, 0, 0, 0, 0],
1508
+ [0, 0, 0, 0, 0, 0, 0],
1509
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
1510
+ out = ndimage.watershed_ift(data, markers)
1511
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
1512
+ [-1, -1, 1, 1, 1, -1, -1],
1513
+ [-1, 1, 1, 1, 1, 1, -1],
1514
+ [-1, 1, 1, 1, 1, 1, -1],
1515
+ [-1, 1, 1, 1, 1, 1, -1],
1516
+ [-1, -1, 1, 1, 1, -1, -1],
1517
+ [-1, -1, -1, -1, -1, -1, -1],
1518
+ [-1, -1, -1, -1, -1, -1, -1]]
1519
+ assert_array_almost_equal(out, xp.asarray(expected))
1520
+
1521
+ def test_watershed_ift03(self, xp):
1522
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
1523
+ [0, 1, 1, 1, 1, 1, 0],
1524
+ [0, 1, 0, 1, 0, 1, 0],
1525
+ [0, 1, 0, 1, 0, 1, 0],
1526
+ [0, 1, 0, 1, 0, 1, 0],
1527
+ [0, 1, 1, 1, 1, 1, 0],
1528
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
1529
+ markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
1530
+ [0, 0, 0, 0, 0, 0, 0],
1531
+ [0, 0, 0, 0, 0, 0, 0],
1532
+ [0, 0, 2, 0, 3, 0, 0],
1533
+ [0, 0, 0, 0, 0, 0, 0],
1534
+ [0, 0, 0, 0, 0, 0, 0],
1535
+ [0, 0, 0, 0, 0, 0, -1]], dtype=xp.int8)
1536
+ out = ndimage.watershed_ift(data, markers)
1537
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
1538
+ [-1, -1, 2, -1, 3, -1, -1],
1539
+ [-1, 2, 2, 3, 3, 3, -1],
1540
+ [-1, 2, 2, 3, 3, 3, -1],
1541
+ [-1, 2, 2, 3, 3, 3, -1],
1542
+ [-1, -1, 2, -1, 3, -1, -1],
1543
+ [-1, -1, -1, -1, -1, -1, -1]]
1544
+ assert_array_almost_equal(out, xp.asarray(expected))
1545
+
1546
+ def test_watershed_ift04(self, xp):
1547
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
1548
+ [0, 1, 1, 1, 1, 1, 0],
1549
+ [0, 1, 0, 1, 0, 1, 0],
1550
+ [0, 1, 0, 1, 0, 1, 0],
1551
+ [0, 1, 0, 1, 0, 1, 0],
1552
+ [0, 1, 1, 1, 1, 1, 0],
1553
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
1554
+ markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
1555
+ [0, 0, 0, 0, 0, 0, 0],
1556
+ [0, 0, 0, 0, 0, 0, 0],
1557
+ [0, 0, 2, 0, 3, 0, 0],
1558
+ [0, 0, 0, 0, 0, 0, 0],
1559
+ [0, 0, 0, 0, 0, 0, 0],
1560
+ [0, 0, 0, 0, 0, 0, -1]],
1561
+ dtype=xp.int8)
1562
+
1563
+ structure=xp.asarray([[1, 1, 1],
1564
+ [1, 1, 1],
1565
+ [1, 1, 1]])
1566
+ out = ndimage.watershed_ift(data, markers, structure=structure)
1567
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
1568
+ [-1, 2, 2, 3, 3, 3, -1],
1569
+ [-1, 2, 2, 3, 3, 3, -1],
1570
+ [-1, 2, 2, 3, 3, 3, -1],
1571
+ [-1, 2, 2, 3, 3, 3, -1],
1572
+ [-1, 2, 2, 3, 3, 3, -1],
1573
+ [-1, -1, -1, -1, -1, -1, -1]]
1574
+ assert_array_almost_equal(out, xp.asarray(expected))
1575
+
1576
+ def test_watershed_ift05(self, xp):
1577
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
1578
+ [0, 1, 1, 1, 1, 1, 0],
1579
+ [0, 1, 0, 1, 0, 1, 0],
1580
+ [0, 1, 0, 1, 0, 1, 0],
1581
+ [0, 1, 0, 1, 0, 1, 0],
1582
+ [0, 1, 1, 1, 1, 1, 0],
1583
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
1584
+ markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
1585
+ [0, 0, 0, 0, 0, 0, 0],
1586
+ [0, 0, 0, 0, 0, 0, 0],
1587
+ [0, 0, 3, 0, 2, 0, 0],
1588
+ [0, 0, 0, 0, 0, 0, 0],
1589
+ [0, 0, 0, 0, 0, 0, 0],
1590
+ [0, 0, 0, 0, 0, 0, -1]],
1591
+ dtype=xp.int8)
1592
+ structure = xp.asarray([[1, 1, 1],
1593
+ [1, 1, 1],
1594
+ [1, 1, 1]])
1595
+ out = ndimage.watershed_ift(data, markers, structure=structure)
1596
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
1597
+ [-1, 3, 3, 2, 2, 2, -1],
1598
+ [-1, 3, 3, 2, 2, 2, -1],
1599
+ [-1, 3, 3, 2, 2, 2, -1],
1600
+ [-1, 3, 3, 2, 2, 2, -1],
1601
+ [-1, 3, 3, 2, 2, 2, -1],
1602
+ [-1, -1, -1, -1, -1, -1, -1]]
1603
+ assert_array_almost_equal(out, xp.asarray(expected))
1604
+
1605
+ def test_watershed_ift06(self, xp):
1606
+ data = xp.asarray([[0, 1, 0, 0, 0, 1, 0],
1607
+ [0, 1, 0, 0, 0, 1, 0],
1608
+ [0, 1, 0, 0, 0, 1, 0],
1609
+ [0, 1, 1, 1, 1, 1, 0],
1610
+ [0, 0, 0, 0, 0, 0, 0],
1611
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
1612
+ markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
1613
+ [0, 0, 0, 1, 0, 0, 0],
1614
+ [0, 0, 0, 0, 0, 0, 0],
1615
+ [0, 0, 0, 0, 0, 0, 0],
1616
+ [0, 0, 0, 0, 0, 0, 0],
1617
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
1618
+ structure=xp.asarray([[1, 1, 1],
1619
+ [1, 1, 1],
1620
+ [1, 1, 1]])
1621
+ out = ndimage.watershed_ift(data, markers, structure=structure)
1622
+ expected = [[-1, 1, 1, 1, 1, 1, -1],
1623
+ [-1, 1, 1, 1, 1, 1, -1],
1624
+ [-1, 1, 1, 1, 1, 1, -1],
1625
+ [-1, 1, 1, 1, 1, 1, -1],
1626
+ [-1, -1, -1, -1, -1, -1, -1],
1627
+ [-1, -1, -1, -1, -1, -1, -1]]
1628
+ assert_array_almost_equal(out, xp.asarray(expected))
1629
+
1630
+ @skip_xp_backends(np_only=True, reason="inplace ops are numpy-specific")
1631
+ def test_watershed_ift07(self, xp):
1632
+ shape = (7, 6)
1633
+ data = np.zeros(shape, dtype=np.uint8)
1634
+ data = data.transpose()
1635
+ data[...] = np.asarray([[0, 1, 0, 0, 0, 1, 0],
1636
+ [0, 1, 0, 0, 0, 1, 0],
1637
+ [0, 1, 0, 0, 0, 1, 0],
1638
+ [0, 1, 1, 1, 1, 1, 0],
1639
+ [0, 0, 0, 0, 0, 0, 0],
1640
+ [0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8)
1641
+ data = xp.asarray(data)
1642
+ markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
1643
+ [0, 0, 0, 1, 0, 0, 0],
1644
+ [0, 0, 0, 0, 0, 0, 0],
1645
+ [0, 0, 0, 0, 0, 0, 0],
1646
+ [0, 0, 0, 0, 0, 0, 0],
1647
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
1648
+ out = xp.zeros(shape, dtype=xp.int16)
1649
+ out = out.T
1650
+ structure=xp.asarray([[1, 1, 1],
1651
+ [1, 1, 1],
1652
+ [1, 1, 1]])
1653
+ ndimage.watershed_ift(data, markers, structure=structure,
1654
+ output=out)
1655
+ expected = [[-1, 1, 1, 1, 1, 1, -1],
1656
+ [-1, 1, 1, 1, 1, 1, -1],
1657
+ [-1, 1, 1, 1, 1, 1, -1],
1658
+ [-1, 1, 1, 1, 1, 1, -1],
1659
+ [-1, -1, -1, -1, -1, -1, -1],
1660
+ [-1, -1, -1, -1, -1, -1, -1]]
1661
+ assert_array_almost_equal(out, xp.asarray(expected))
1662
+
1663
+ @skip_xp_backends("cupy", reason="no watershed_ift on CuPy")
1664
+ def test_watershed_ift08(self, xp):
1665
+ # Test cost larger than uint8. See gh-10069.
1666
+ data = xp.asarray([[256, 0],
1667
+ [0, 0]], dtype=xp.uint16)
1668
+ markers = xp.asarray([[1, 0],
1669
+ [0, 0]], dtype=xp.int8)
1670
+ out = ndimage.watershed_ift(data, markers)
1671
+ expected = [[1, 1],
1672
+ [1, 1]]
1673
+ assert_array_almost_equal(out, xp.asarray(expected))
1674
+
1675
+ @skip_xp_backends("cupy", reason="no watershed_ift on CuPy")
1676
+ def test_watershed_ift09(self, xp):
1677
+ # Test large cost. See gh-19575
1678
+ data = xp.asarray([[xp.iinfo(xp.uint16).max, 0],
1679
+ [0, 0]], dtype=xp.uint16)
1680
+ markers = xp.asarray([[1, 0],
1681
+ [0, 0]], dtype=xp.int8)
1682
+ out = ndimage.watershed_ift(data, markers)
1683
+ expected = [[1, 1],
1684
+ [1, 1]]
1685
+ xp_assert_close(out, xp.asarray(expected), check_dtype=False)
1686
+
1687
+
1688
+ @skip_xp_backends(np_only=True)
1689
+ @pytest.mark.parametrize("dt", [np.intc, np.uintc])
1690
+ @make_xp_test_case(ndimage.value_indices)
1691
+ def test_gh_19423(dt, xp):
1692
+ rng = np.random.default_rng(123)
1693
+ max_val = 8
1694
+ image = rng.integers(low=0, high=max_val, size=(10, 12)).astype(dtype=dt)
1695
+ val_idx = ndimage.value_indices(image)
1696
+ assert len(val_idx.keys()) == max_val
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_morphology.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_ni_support.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import numpy as np
4
+ from .._ni_support import _get_output
5
+
6
+
7
+ @pytest.mark.parametrize(
8
+ 'dtype',
9
+ [
10
+ # String specifiers
11
+ 'f4', 'float32', 'complex64', 'complex128',
12
+ # Type and dtype specifiers
13
+ np.float32, float, np.dtype('f4'),
14
+ # Derive from input
15
+ None,
16
+ ],
17
+ )
18
+ def test_get_output_basic(dtype):
19
+ shape = (2, 3)
20
+
21
+ input_ = np.zeros(shape, dtype='float32')
22
+
23
+ # For None, derive dtype from input
24
+ expected_dtype = 'float32' if dtype is None else dtype
25
+
26
+ # Output is dtype-specifier, retrieve shape from input
27
+ result = _get_output(dtype, input_)
28
+ assert result.shape == shape
29
+ assert result.dtype == np.dtype(expected_dtype)
30
+
31
+ # Output is dtype specifier, with explicit shape, overriding input
32
+ result = _get_output(dtype, input_, shape=(3, 2))
33
+ assert result.shape == (3, 2)
34
+ assert result.dtype == np.dtype(expected_dtype)
35
+
36
+ # Output is pre-allocated array, return directly
37
+ output = np.zeros(shape, dtype=dtype)
38
+ result = _get_output(output, input_)
39
+ assert result is output
40
+
41
+
42
+ def test_get_output_complex():
43
+ shape = (2, 3)
44
+
45
+ input_ = np.zeros(shape)
46
+
47
+ # None, promote input type to complex
48
+ result = _get_output(None, input_, complex_output=True)
49
+ assert result.shape == shape
50
+ assert result.dtype == np.dtype('complex128')
51
+
52
+ # Explicit type, promote type to complex
53
+ with pytest.warns(UserWarning, match='promoting specified output dtype to complex'):
54
+ result = _get_output(float, input_, complex_output=True)
55
+ assert result.shape == shape
56
+ assert result.dtype == np.dtype('complex128')
57
+
58
+ # String specifier, simply verify complex output
59
+ result = _get_output('complex64', input_, complex_output=True)
60
+ assert result.shape == shape
61
+ assert result.dtype == np.dtype('complex64')
62
+
63
+
64
+ def test_get_output_error_cases():
65
+ input_ = np.zeros((2, 3), 'float32')
66
+
67
+ # Two separate paths can raise the same error
68
+ with pytest.raises(RuntimeError, match='output must have complex dtype'):
69
+ _get_output('float32', input_, complex_output=True)
70
+ with pytest.raises(RuntimeError, match='output must have complex dtype'):
71
+ _get_output(np.zeros((2, 3)), input_, complex_output=True)
72
+
73
+ with pytest.raises(RuntimeError, match='output must have numeric dtype'):
74
+ _get_output('void', input_)
75
+
76
+ with pytest.raises(RuntimeError, match='shape not correct'):
77
+ _get_output(np.zeros((3, 2)), input_)