FaustDerLegende commited on
Commit
b455217
·
verified ·
1 Parent(s): aa1d54c

Upload folder using huggingface_hub (part 15)

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 +40 -0
  2. .venv/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_6_data.npz +3 -0
  3. .venv/lib/python3.12/site-packages/scipy/linalg/tests/data/gendare_20170120_data.npz +3 -0
  4. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_basic.py +0 -0
  5. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_batch.py +742 -0
  6. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_blas.py +1133 -0
  7. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cython_abi.py +120 -0
  8. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cython_blas.py +147 -0
  9. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cython_lapack.py +56 -0
  10. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py +161 -0
  11. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp.py +0 -0
  12. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_cholesky.py +452 -0
  13. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_cossin.py +314 -0
  14. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_ldl.py +136 -0
  15. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_lu.py +310 -0
  16. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_polar.py +110 -0
  17. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_update.py +1704 -0
  18. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_deprecations.py +223 -0
  19. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_extending.py +55 -0
  20. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_fblas.py +610 -0
  21. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_interpolative.py +232 -0
  22. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_lapack.py +0 -0
  23. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_matfuncs.py +1149 -0
  24. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py +136 -0
  25. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_procrustes.py +209 -0
  26. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_sketches.py +112 -0
  27. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_solve_toeplitz.py +137 -0
  28. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_solvers.py +862 -0
  29. .venv/lib/python3.12/site-packages/scipy/linalg/tests/test_special_matrices.py +619 -0
  30. .venv/lib/python3.12/site-packages/scipy/misc/__init__.py +6 -0
  31. .venv/lib/python3.12/site-packages/scipy/misc/common.py +6 -0
  32. .venv/lib/python3.12/site-packages/scipy/misc/doccer.py +6 -0
  33. .venv/lib/python3.12/site-packages/scipy/ndimage/__init__.py +174 -0
  34. .venv/lib/python3.12/site-packages/scipy/ndimage/_ctest.cpython-312-x86_64-linux-gnu.so +0 -0
  35. .venv/lib/python3.12/site-packages/scipy/ndimage/_cytest.cpython-312-x86_64-linux-gnu.so +0 -0
  36. .venv/lib/python3.12/site-packages/scipy/ndimage/_delegators.py +303 -0
  37. .venv/lib/python3.12/site-packages/scipy/ndimage/_filters.py +2446 -0
  38. .venv/lib/python3.12/site-packages/scipy/ndimage/_fourier.py +306 -0
  39. .venv/lib/python3.12/site-packages/scipy/ndimage/_interpolation.py +1033 -0
  40. .venv/lib/python3.12/site-packages/scipy/ndimage/_measurements.py +1689 -0
  41. .venv/lib/python3.12/site-packages/scipy/ndimage/_morphology.py +0 -0
  42. .venv/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-x86_64-linux-gnu.so +3 -0
  43. .venv/lib/python3.12/site-packages/scipy/ndimage/_ndimage_api.py +16 -0
  44. .venv/lib/python3.12/site-packages/scipy/ndimage/_ni_docstrings.py +220 -0
  45. .venv/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-x86_64-linux-gnu.so +3 -0
  46. .venv/lib/python3.12/site-packages/scipy/ndimage/_ni_support.py +139 -0
  47. .venv/lib/python3.12/site-packages/scipy/ndimage/_rank_filter_1d.cpython-312-x86_64-linux-gnu.so +0 -0
  48. .venv/lib/python3.12/site-packages/scipy/ndimage/_support_alternative_backends.py +122 -0
  49. .venv/lib/python3.12/site-packages/scipy/ndimage/filters.py +27 -0
  50. .venv/lib/python3.12/site-packages/scipy/ndimage/fourier.py +21 -0
.gitattributes CHANGED
@@ -345,3 +345,43 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
345
  .venv/lib/python3.12/site-packages/scipy/linalg/_solve_toeplitz.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
346
  .venv/lib/python3.12/site-packages/scipy/linalg/cython_blas.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
347
  .venv/lib/python3.12/site-packages/scipy/linalg/cython_lapack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345
  .venv/lib/python3.12/site-packages/scipy/linalg/_solve_toeplitz.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
346
  .venv/lib/python3.12/site-packages/scipy/linalg/cython_blas.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
347
  .venv/lib/python3.12/site-packages/scipy/linalg/cython_lapack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
348
+ .venv/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
349
+ .venv/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
350
+ .venv/lib/python3.12/site-packages/scipy/odr/__odrpack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
351
+ .venv/lib/python3.12/site-packages/scipy/optimize/_bglu_dense.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
352
+ .venv/lib/python3.12/site-packages/scipy/optimize/_highspy/_core.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
353
+ .venv/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_options.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
354
+ .venv/lib/python3.12/site-packages/scipy/optimize/_minpack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
355
+ .venv/lib/python3.12/site-packages/scipy/optimize/_moduleTNC.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
356
+ .venv/lib/python3.12/site-packages/scipy/optimize/_pava_pybind.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
357
+ .venv/lib/python3.12/site-packages/scipy/optimize/_trlib/_trlib.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
358
+ .venv/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
359
+ .venv/lib/python3.12/site-packages/scipy/signal/_peak_finding_utils.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
360
+ .venv/lib/python3.12/site-packages/scipy/signal/_sigtools.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
361
+ .venv/lib/python3.12/site-packages/scipy/signal/_sosfilt.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
362
+ .venv/lib/python3.12/site-packages/scipy/signal/_upfirdn_apply.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
363
+ .venv/lib/python3.12/site-packages/scipy/sparse/_csparsetools.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
364
+ .venv/lib/python3.12/site-packages/scipy/sparse/_sparsetools.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
365
+ .venv/lib/python3.12/site-packages/scipy/sparse/csgraph/_flow.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
366
+ .venv/lib/python3.12/site-packages/scipy/sparse/csgraph/_matching.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
367
+ .venv/lib/python3.12/site-packages/scipy/sparse/csgraph/_reordering.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
368
+ .venv/lib/python3.12/site-packages/scipy/sparse/csgraph/_shortest_path.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
369
+ .venv/lib/python3.12/site-packages/scipy/sparse/csgraph/_tools.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
370
+ .venv/lib/python3.12/site-packages/scipy/sparse/csgraph/_traversal.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
371
+ .venv/lib/python3.12/site-packages/scipy/sparse/linalg/_dsolve/_superlu.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
372
+ .venv/lib/python3.12/site-packages/scipy/sparse/linalg/_eigen/arpack/_arpacklib.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
373
+ .venv/lib/python3.12/site-packages/scipy/sparse/linalg/_propack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
374
+ .venv/lib/python3.12/site-packages/scipy/spatial/_ckdtree.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
375
+ .venv/lib/python3.12/site-packages/scipy/spatial/_distance_pybind.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
376
+ .venv/lib/python3.12/site-packages/scipy/spatial/_distance_wrap.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
377
+ .venv/lib/python3.12/site-packages/scipy/spatial/_qhull.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
378
+ .venv/lib/python3.12/site-packages/scipy/spatial/transform/_rigid_transform_cy.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
379
+ .venv/lib/python3.12/site-packages/scipy/spatial/transform/_rotation_cy.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
380
+ .venv/lib/python3.12/site-packages/scipy/special/__pycache__/_basic.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
381
+ .venv/lib/python3.12/site-packages/scipy/special/_ellip_harm_2.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
382
+ .venv/lib/python3.12/site-packages/scipy/special/_gufuncs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
383
+ .venv/lib/python3.12/site-packages/scipy/special/_specfun.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
384
+ .venv/lib/python3.12/site-packages/scipy/special/_special_ufuncs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
385
+ .venv/lib/python3.12/site-packages/scipy/special/_ufuncs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
386
+ .venv/lib/python3.12/site-packages/scipy/special/_ufuncs_cxx.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
387
+ .venv/lib/python3.12/site-packages/scipy/special/cython_special.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_6_data.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b2a0736b541ebf5c4b9b4c00d6dab281e73c9fb9913c6e2581a781b37b602f9
3
+ size 15878
.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/gendare_20170120_data.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a3dfab451d9d5c20243e0ed85cd8b6c9657669fb9a0f83b5be165585783d55b5
3
+ size 2164
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_basic.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_batch.py ADDED
@@ -0,0 +1,742 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import pytest
3
+ import numpy as np
4
+ from numpy.testing import assert_allclose
5
+ from scipy import linalg, sparse
6
+
7
+
8
+ real_floating = [np.float32, np.float64]
9
+ complex_floating = [np.complex64, np.complex128]
10
+ floating = real_floating + complex_floating
11
+
12
+
13
+ def get_random(shape, *, dtype, rng):
14
+ A = rng.random(shape)
15
+ if np.issubdtype(dtype, np.complexfloating):
16
+ A = A + rng.random(shape) * 1j
17
+ return A.astype(dtype)
18
+
19
+ def get_nearly_hermitian(shape, dtype, atol, rng):
20
+ # Generate a batch of nearly Hermitian matrices with specified
21
+ # `shape` and `dtype`. `atol` controls the level of noise in
22
+ # Hermitian-ness to by generated by `rng`.
23
+ A = rng.random(shape).astype(dtype)
24
+ At = np.conj(A.swapaxes(-1, -2))
25
+ noise = rng.standard_normal(size=A.shape).astype(dtype) * atol
26
+ return A + At + noise
27
+
28
+
29
+ class TestBatch:
30
+ # Test batch support for most linalg functions
31
+
32
+ def batch_test(self, fun, arrays, *, core_dim=2, n_out=1, kwargs=None, dtype=None,
33
+ broadcast=True, check_kwargs=True):
34
+ # Check that all outputs of batched call `fun(A, **kwargs)` are the same
35
+ # as if we loop over the separate vectors/matrices in `A`. Also check
36
+ # that `fun` accepts `A` by position or keyword and that results are
37
+ # identical. This is important because the name of the array argument
38
+ # is manually specified to the decorator, and it's easy to mess up.
39
+ # However, this makes it hard to test positional arguments passed
40
+ # after the array, so we test that separately for a few functions to
41
+ # make sure the decorator is working as it should.
42
+
43
+ kwargs = {} if kwargs is None else kwargs
44
+ parameters = list(inspect.signature(fun).parameters.keys())
45
+ arrays = (arrays,) if not isinstance(arrays, tuple) else arrays
46
+
47
+ # Identical results when passing argument by keyword or position
48
+ res2 = fun(*arrays, **kwargs)
49
+ if check_kwargs:
50
+ res1 = fun(**dict(zip(parameters, arrays)), **kwargs)
51
+ for out1, out2 in zip(res1, res2): # even a single array is iterable...
52
+ np.testing.assert_equal(out1, out2)
53
+
54
+ # Check results vs looping over
55
+ res = (res2,) if n_out == 1 else res2
56
+ # This is not the general behavior (only batch dimensions get
57
+ # broadcasted by the decorator) but it's easier for testing.
58
+ if broadcast:
59
+ arrays = np.broadcast_arrays(*arrays)
60
+ batch_shape = arrays[0].shape[:-core_dim]
61
+ for i in range(batch_shape[0]):
62
+ for j in range(batch_shape[1]):
63
+ arrays_ij = (array[i, j] for array in arrays)
64
+ ref = fun(*arrays_ij, **kwargs)
65
+ # see gh-25508:
66
+ if (np.dtype(np.int_).itemsize == 4 and
67
+ n_out > 1 and isinstance(ref[0], int)):
68
+ ref = tuple(np.asarray(refk, dtype=np.int64) for refk in ref)
69
+ else:
70
+ ref = ((np.asarray(ref),) if n_out == 1 else
71
+ tuple(np.asarray(refk) for refk in ref))
72
+ for k in range(n_out):
73
+ assert_allclose(res[k][i, j], ref[k])
74
+ assert np.shape(res[k][i, j]) == ref[k].shape
75
+
76
+ for k in range(len(ref)):
77
+ out_dtype = ref[k].dtype if dtype is None else dtype
78
+ assert res[k].dtype == out_dtype
79
+
80
+ return res2 # return original, non-tuplized result
81
+
82
+ @pytest.mark.parametrize('dtype', floating)
83
+ def test_expm_cond(self, dtype):
84
+ rng = np.random.default_rng(8342310302941288912051)
85
+ A = rng.random((5, 3, 4, 4)).astype(dtype)
86
+ self.batch_test(linalg.expm_cond, A)
87
+
88
+ @pytest.mark.parametrize('dtype', floating)
89
+ def test_issymmetric(self, dtype):
90
+ rng = np.random.default_rng(8342310302941288912051)
91
+ A = get_nearly_hermitian((5, 3, 4, 4), dtype, 3e-4, rng)
92
+ res = self.batch_test(linalg.issymmetric, A, kwargs=dict(atol=1e-3))
93
+ assert not np.all(res) # ensure test is not trivial: not all True or False;
94
+ assert np.any(res) # also confirms that `atol` is passed to issymmetric
95
+
96
+ @pytest.mark.parametrize('dtype', floating)
97
+ def test_ishermitian(self, dtype):
98
+ rng = np.random.default_rng(8342310302941288912051)
99
+ A = get_nearly_hermitian((5, 3, 4, 4), dtype, 3e-4, rng)
100
+ res = self.batch_test(linalg.ishermitian, A, kwargs=dict(atol=1e-3))
101
+ assert not np.all(res) # ensure test is not trivial: not all True or False;
102
+ assert np.any(res) # also confirms that `atol` is passed to ishermitian
103
+
104
+ @pytest.mark.parametrize('dtype', floating)
105
+ def test_diagsvd(self, dtype):
106
+ rng = np.random.default_rng(8342310302941288912051)
107
+ A = rng.random((5, 3, 4)).astype(dtype)
108
+ res1 = self.batch_test(linalg.diagsvd, A, kwargs=dict(M=6, N=4), core_dim=1)
109
+ # test that `M, N` can be passed by position
110
+ res2 = linalg.diagsvd(A, 6, 4)
111
+ np.testing.assert_equal(res1, res2)
112
+
113
+ @pytest.mark.parametrize('fun', [linalg.inv, linalg.sqrtm, linalg.signm,
114
+ linalg.sinm, linalg.cosm, linalg.tanhm,
115
+ linalg.sinhm, linalg.coshm, linalg.tanhm,
116
+ linalg.pinv, linalg.pinvh, linalg.orth])
117
+ @pytest.mark.parametrize('dtype', floating)
118
+ def test_matmat(self, fun, dtype): # matrix in, matrix out
119
+ rng = np.random.default_rng(8342310302941288912051)
120
+ A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng)
121
+
122
+ # sqrtm can return complex output for real input resulting in i/o type
123
+ # mismatch. Nudge the eigenvalues to positive side to avoid this.
124
+ if fun == linalg.sqrtm:
125
+ A = A + 3*np.eye(4, dtype=dtype)
126
+
127
+ self.batch_test(fun, A)
128
+
129
+ @pytest.mark.parametrize('dtype', floating)
130
+ def test_null_space(self, dtype):
131
+ rng = np.random.default_rng(8342310302941288912051)
132
+ A = get_random((5, 3, 4, 6), dtype=dtype, rng=rng)
133
+ self.batch_test(linalg.null_space, A)
134
+
135
+ @pytest.mark.parametrize('dtype', floating)
136
+ def test_funm(self, dtype):
137
+ rng = np.random.default_rng(8342310302941288912051)
138
+ A = get_random((2, 4, 3, 3), dtype=dtype, rng=rng)
139
+ self.batch_test(linalg.funm, A, kwargs=dict(func=np.sin))
140
+
141
+ @pytest.mark.parametrize('dtype', floating)
142
+ def test_fractional_matrix_power(self, dtype):
143
+ rng = np.random.default_rng(8342310302941288912051)
144
+ A = get_random((2, 4, 3, 3), dtype=dtype, rng=rng)
145
+ res1 = self.batch_test(linalg.fractional_matrix_power, A, kwargs={'t':1.5})
146
+ # test that `t` can be passed by position
147
+ res2 = linalg.fractional_matrix_power(A, 1.5)
148
+ np.testing.assert_equal(res1, res2)
149
+
150
+ @pytest.mark.parametrize('dtype', floating)
151
+ def test_logm(self, dtype):
152
+ # One test failed absolute tolerance with default random seed
153
+ rng = np.random.default_rng(89940026998903887141749720079406074936)
154
+ A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng)
155
+ A = A + 3*np.eye(4) # avoid complex output for real input
156
+ res1 = self.batch_test(linalg.logm, A)
157
+ # test that `disp` can be passed by position
158
+ res2 = linalg.logm(A)
159
+ for res1i, res2i in zip(res1, res2):
160
+ np.testing.assert_equal(res1i, res2i)
161
+
162
+ @pytest.mark.parametrize('dtype', floating)
163
+ def test_pinv(self, dtype):
164
+ rng = np.random.default_rng(8342310302941288912051)
165
+ A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng)
166
+ self.batch_test(linalg.pinv, A, n_out=2, kwargs=dict(return_rank=True))
167
+
168
+ @pytest.mark.parametrize('dtype', floating)
169
+ def test_matrix_balance(self, dtype):
170
+ rng = np.random.default_rng(8342310302941288912051)
171
+ A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng)
172
+ self.batch_test(linalg.matrix_balance, A, n_out=2)
173
+ self.batch_test(linalg.matrix_balance, A, n_out=2, kwargs={'separate':True})
174
+
175
+ @pytest.mark.parametrize('dtype', floating)
176
+ def test_bandwidth(self, dtype):
177
+ rng = np.random.default_rng(8342310302941288912051)
178
+ A = get_random((4, 4), dtype=dtype, rng=rng)
179
+ A = np.asarray([np.triu(A, k) for k in range(-3, 3)]).reshape((2, 3, 4, 4))
180
+ self.batch_test(linalg.bandwidth, A, n_out=2)
181
+
182
+ @pytest.mark.parametrize('fun_n_out', [(linalg.cholesky, 1), (linalg.ldl, 3),
183
+ (linalg.cho_factor, 2)])
184
+ @pytest.mark.parametrize('dtype', floating)
185
+ def test_ldl_cholesky(self, fun_n_out, dtype):
186
+ rng = np.random.default_rng(8342310302941288912051)
187
+ fun, n_out = fun_n_out
188
+ A = get_nearly_hermitian((5, 3, 4, 4), dtype, 0, rng) # exactly Hermitian
189
+ A = A + 4*np.eye(4, dtype=dtype) # ensure positive definite for Cholesky
190
+ self.batch_test(fun, A, n_out=n_out)
191
+
192
+ @pytest.mark.parametrize('compute_uv', [False, True])
193
+ @pytest.mark.parametrize('full_matrices', [False, True])
194
+ @pytest.mark.parametrize('dtype', floating)
195
+ def test_svd(self, compute_uv, full_matrices, dtype):
196
+ rng = np.random.default_rng(8342310302941288912051)
197
+ A = get_random((5, 3, 2, 4), dtype=dtype, rng=rng)
198
+ n_out = 3 if compute_uv else 1
199
+ self.batch_test(
200
+ linalg.svd, A, n_out=n_out,
201
+ kwargs=dict(compute_uv=compute_uv, full_matrices=full_matrices)
202
+ )
203
+
204
+ A = get_random((5, 3, 2, 0), dtype=dtype, rng=rng)
205
+ self.batch_test(
206
+ linalg.svd, A, n_out=n_out,
207
+ kwargs=dict(compute_uv=compute_uv, full_matrices=full_matrices)
208
+ )
209
+
210
+ @pytest.mark.parametrize('fun', [linalg.polar, linalg.rq])
211
+ @pytest.mark.parametrize('dtype', floating)
212
+ def test_polar_qr_rq(self, fun, dtype):
213
+ rng = np.random.default_rng(8342310302941288912051)
214
+ A = get_random((5, 3, 2, 4), dtype=dtype, rng=rng)
215
+ self.batch_test(fun, A, n_out=2)
216
+
217
+ @pytest.mark.parametrize('pivoting', [True, False])
218
+ @pytest.mark.parametrize('dtype', floating)
219
+ @pytest.mark.parametrize('mode', ['full', 'economic', 'r'])
220
+ def test_qr(self, mode, dtype, pivoting):
221
+ rng = np.random.default_rng(12345)
222
+ a = get_random((5, 3, 2, 4), dtype=dtype, rng=rng)
223
+ self.batch_test(lambda x: linalg.qr(x, mode=mode, pivoting=pivoting), a,
224
+ n_out=(1 if mode == 'r' else 2) + 1 if pivoting else 0)
225
+
226
+ @pytest.mark.parametrize('pivoting', [True, False])
227
+ @pytest.mark.parametrize('dtype', floating)
228
+ def test_qr_raw(self, dtype, pivoting):
229
+ rng = np.random.default_rng(12345)
230
+ a = get_random((5, 3, 2, 4), dtype=dtype, rng=rng)
231
+ (q_raw, tau), r, *other = linalg.qr(a, mode="raw", pivoting=pivoting)
232
+
233
+ # return argument contains a tuple, hence `batch_test` is not applicable.
234
+ for i in range(a.shape[0]):
235
+ for j in range(a.shape[1]):
236
+ (q_raw_ij, tau_ij), r_ij, *other_ij = linalg.qr(
237
+ a[i, j, :, :], mode="raw", pivoting=pivoting
238
+ )
239
+
240
+ assert_allclose(q_raw[i, j, :, :], q_raw_ij)
241
+ assert_allclose(tau[i, j, :], tau_ij)
242
+ assert_allclose(r[i, j, :, :], r_ij)
243
+
244
+ if pivoting:
245
+ assert_allclose(other[0][i, j, :], other_ij[0])
246
+
247
+
248
+ @pytest.mark.parametrize('cdim', [(5,), (5, 4), (2, 3, 5, 4)])
249
+ @pytest.mark.parametrize('dtype', floating)
250
+ def test_qr_multiply(self, cdim, dtype):
251
+ rng = np.random.default_rng(8342310302941288912051)
252
+ A = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
253
+ c = get_random(cdim, dtype=dtype, rng=rng)
254
+ res = linalg.qr_multiply(A, c, mode='left')
255
+ q, r = linalg.qr(A)
256
+ ref = q @ c
257
+ atol = 1e-6 if dtype in {np.float32, np.complex64} else 1e-12
258
+ assert_allclose(res[0], ref, atol=atol)
259
+ assert_allclose(res[1], r, atol=atol)
260
+
261
+ @pytest.mark.parametrize('uvdim', [[(5,), (3,)], [(4, 5, 2), (4, 3, 2)]])
262
+ @pytest.mark.parametrize('dtype', floating)
263
+ def test_qr_update(self, uvdim, dtype):
264
+ rng = np.random.default_rng(8342310302941288912051)
265
+ udim, vdim = uvdim
266
+ A = get_random((4, 5, 3), dtype=dtype, rng=rng)
267
+ u = get_random(udim, dtype=dtype, rng=rng)
268
+ v = get_random(vdim, dtype=dtype, rng=rng)
269
+ q, r = linalg.qr(A)
270
+ res = linalg.qr_update(q, r, u, v)
271
+ for i in range(4):
272
+ qi, ri = q[i], r[i]
273
+ ui, vi = (u, v) if u.ndim == 1 else (u[i], v[i])
274
+ ref_i = linalg.qr_update(qi, ri, ui, vi)
275
+ assert_allclose(res[0][i], ref_i[0])
276
+ assert_allclose(res[1][i], ref_i[1])
277
+
278
+ @pytest.mark.parametrize('udim', [(5,), (4, 3, 5)])
279
+ @pytest.mark.parametrize('kdim', [(), (4,)])
280
+ @pytest.mark.parametrize('dtype', floating)
281
+ def test_qr_insert(self, udim, kdim, dtype):
282
+ rng = np.random.default_rng(8342310302941288912051)
283
+ A = get_random((4, 5, 5), dtype=dtype, rng=rng)
284
+ u = get_random(udim, dtype=dtype, rng=rng)
285
+ k = rng.integers(0, 5, size=kdim)
286
+ q, r = linalg.qr(A)
287
+ res = linalg.qr_insert(q, r, u, k)
288
+ for i in range(4):
289
+ qi, ri = q[i], r[i]
290
+ ki = k if k.ndim == 0 else k[i]
291
+ ui = u if u.ndim == 1 else u[i]
292
+ ref_i = linalg.qr_insert(qi, ri, ui, ki)
293
+ assert_allclose(res[0][i], ref_i[0])
294
+ assert_allclose(res[1][i], ref_i[1])
295
+
296
+ @pytest.mark.parametrize('kdim', [(), (4,)])
297
+ @pytest.mark.parametrize('dtype', floating)
298
+ def test_qr_delete(self, kdim, dtype):
299
+ rng = np.random.default_rng(8342310302941288912051)
300
+ A = get_random((4, 5, 5), dtype=dtype, rng=rng)
301
+ k = rng.integers(0, 4, size=kdim)
302
+ q, r = linalg.qr(A)
303
+ res = linalg.qr_delete(q, r, k)
304
+ for i in range(4):
305
+ qi, ri = q[i], r[i]
306
+ ki = k if k.ndim == 0 else k[i]
307
+ ref_i = linalg.qr_delete(qi, ri, ki)
308
+ assert_allclose(res[0][i], ref_i[0])
309
+ assert_allclose(res[1][i], ref_i[1])
310
+
311
+ @pytest.mark.parametrize('fun', [linalg.schur, linalg.lu_factor])
312
+ @pytest.mark.parametrize('dtype', floating)
313
+ def test_schur_lu(self, fun, dtype):
314
+ rng = np.random.default_rng(8342310302941288912051)
315
+ A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng)
316
+ self.batch_test(fun, A, n_out=2)
317
+
318
+ @pytest.mark.parametrize('calc_q', [False, True])
319
+ @pytest.mark.parametrize('dtype', floating)
320
+ def test_hessenberg(self, calc_q, dtype):
321
+ rng = np.random.default_rng(8342310302941288912051)
322
+ A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng)
323
+ n_out = 2 if calc_q else 1
324
+ self.batch_test(linalg.hessenberg, A, n_out=n_out, kwargs=dict(calc_q=calc_q))
325
+
326
+ @pytest.mark.parametrize('eigvals_only', [False, True])
327
+ @pytest.mark.parametrize('dtype', floating)
328
+ def test_eig_banded(self, eigvals_only, dtype):
329
+ rng = np.random.default_rng(8342310302941288912051)
330
+ A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng)
331
+ n_out = 1 if eigvals_only else 2
332
+ self.batch_test(linalg.eig_banded, A, n_out=n_out,
333
+ kwargs=dict(eigvals_only=eigvals_only))
334
+
335
+ @pytest.mark.parametrize('dtype', floating)
336
+ def test_eigvals_banded(self, dtype):
337
+ rng = np.random.default_rng(8342310302941288912051)
338
+ A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng)
339
+ self.batch_test(linalg.eigvals_banded, A)
340
+
341
+ @pytest.mark.parametrize('two_in', [False, True])
342
+ @pytest.mark.parametrize('fun_n_nout', [(linalg.eigh, 1), (linalg.eigh, 2),
343
+ (linalg.eigvalsh, 1), (linalg.eigvals, 1)])
344
+ @pytest.mark.parametrize('dtype', floating)
345
+ def test_eigh(self, two_in, fun_n_nout, dtype):
346
+ rng = np.random.default_rng(8342310302941288912051)
347
+ fun, n_out = fun_n_nout
348
+ A = get_nearly_hermitian((1, 3, 4, 4), dtype, 0, rng) # exactly Hermitian
349
+ B = get_nearly_hermitian((2, 1, 4, 4), dtype, 0, rng) # exactly Hermitian
350
+ B = B + 4*np.eye(4).astype(dtype) # needs to be positive definite
351
+ args = (A, B) if two_in else (A,)
352
+ kwargs = dict(eigvals_only=True) if (n_out == 1 and fun==linalg.eigh) else {}
353
+ self.batch_test(fun, args, n_out=n_out, kwargs=kwargs)
354
+
355
+ @pytest.mark.parametrize('compute_expm', [False, True])
356
+ @pytest.mark.parametrize('dtype', floating)
357
+ def test_expm_frechet(self, compute_expm, dtype):
358
+ rng = np.random.default_rng(8342310302941288912051)
359
+ A = get_random((1, 3, 4, 4), dtype=dtype, rng=rng)
360
+ E = get_random((2, 1, 4, 4), dtype=dtype, rng=rng)
361
+ n_out = 2 if compute_expm else 1
362
+ self.batch_test(linalg.expm_frechet, (A, E), n_out=n_out,
363
+ kwargs=dict(compute_expm=compute_expm))
364
+
365
+ @pytest.mark.parametrize('dtype', floating)
366
+ def test_subspace_angles(self, dtype):
367
+ rng = np.random.default_rng(8342310302941288912051)
368
+ A = get_random((1, 3, 4, 3), dtype=dtype, rng=rng)
369
+ B = get_random((2, 1, 4, 3), dtype=dtype, rng=rng)
370
+ self.batch_test(linalg.subspace_angles, (A, B))
371
+ # just to show that A and B don't need to be broadcastable
372
+ M, N, K = 4, 5, 3
373
+ A = get_random((1, 3, M, N), dtype=dtype, rng=rng)
374
+ B = get_random((2, 1, M, K), dtype=dtype, rng=rng)
375
+ assert linalg.subspace_angles(A, B).shape == (2, 3, min(N, K))
376
+
377
+ @pytest.mark.parametrize('fun', [linalg.svdvals])
378
+ @pytest.mark.parametrize('dtype', floating)
379
+ def test_svdvals(self, fun, dtype):
380
+ rng = np.random.default_rng(8342310302941288912051)
381
+ A = get_random((2, 3, 4, 5), dtype=dtype, rng=rng)
382
+ self.batch_test(fun, A)
383
+
384
+ @pytest.mark.parametrize('fun_n_out', [(linalg.orthogonal_procrustes, 2),
385
+ (linalg.khatri_rao, 1),
386
+ (linalg.solve_continuous_lyapunov, 1),
387
+ (linalg.solve_discrete_lyapunov, 1),
388
+ (linalg.qz, 4),
389
+ (linalg.ordqz, 6)])
390
+ @pytest.mark.parametrize('dtype', floating)
391
+ def test_two_generic_matrix_inputs(self, fun_n_out, dtype):
392
+ rng = np.random.default_rng(8342310302941288912051)
393
+ fun, n_out = fun_n_out
394
+ A = get_random((2, 3, 4, 4), dtype=dtype, rng=rng)
395
+ B = get_random((2, 3, 4, 4), dtype=dtype, rng=rng)
396
+ self.batch_test(fun, (A, B), n_out=n_out)
397
+
398
+ @pytest.mark.parametrize('dtype', floating)
399
+ def test_cossin(self, dtype):
400
+ rng = np.random.default_rng(8342310302941288912051)
401
+ p, q = 3, 4
402
+ X = get_random((2, 3, 10, 10), dtype=dtype, rng=rng)
403
+ x11, x12, x21, x22 = (X[..., :p, :q], X[..., :p, q:],
404
+ X[..., p:, :q], X[..., p:, q:])
405
+ res = linalg.cossin(X, p, q)
406
+ ref = linalg.cossin((x11, x12, x21, x22))
407
+ for res_i, ref_i in zip(res, ref):
408
+ np.testing.assert_equal(res_i, ref_i)
409
+
410
+ for j in range(2):
411
+ for k in range(3):
412
+ ref_jk = linalg.cossin(X[j, k], p, q)
413
+ for res_i, ref_ijk in zip(res, ref_jk):
414
+ np.testing.assert_equal(res_i[j, k], ref_ijk)
415
+
416
+ @pytest.mark.parametrize('dtype', floating)
417
+ def test_sylvester(self, dtype):
418
+ rng = np.random.default_rng(8342310302941288912051)
419
+ A = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
420
+ B = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
421
+ C = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
422
+ self.batch_test(linalg.solve_sylvester, (A, B, C))
423
+
424
+ @pytest.mark.parametrize('fun', [linalg.solve_continuous_are,
425
+ linalg.solve_discrete_are])
426
+ @pytest.mark.parametrize('dtype', floating)
427
+ def test_are(self, fun, dtype):
428
+ rng = np.random.default_rng(8342310302941288912051)
429
+ a = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
430
+ b = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
431
+ q = get_nearly_hermitian((2, 3, 5, 5), dtype=dtype, atol=0, rng=rng)
432
+ r = get_nearly_hermitian((2, 3, 5, 5), dtype=dtype, atol=0, rng=rng)
433
+ a = a + 5*np.eye(5) # making these positive definite seems to help
434
+ b = b + 5*np.eye(5)
435
+ q = q + 5*np.eye(5)
436
+ r = r + 5*np.eye(5)
437
+ e = np.eye(5)
438
+ s = np.zeros((5, 5))
439
+ self.batch_test(fun, (a, b, q, r))
440
+ self.batch_test(fun, (a, b, q, r, e))
441
+ self.batch_test(fun, (a, b, q, r, e, s))
442
+
443
+ res = fun(a, b, q, r)
444
+ ref = fun(a, b, q, r, s=s)
445
+ np.testing.assert_allclose(res, ref)
446
+
447
+ @pytest.mark.parametrize('dtype', floating)
448
+ def test_rsf2cs(self, dtype):
449
+ rng = np.random.default_rng(8342310302941288912051)
450
+ A = get_random((2, 3, 4, 4), dtype=dtype, rng=rng)
451
+ T, Z = linalg.schur(A)
452
+ self.batch_test(linalg.rsf2csf, (T, Z), n_out=2)
453
+
454
+ @pytest.mark.parametrize('dtype', floating)
455
+ def test_cholesky_banded(self, dtype):
456
+ rng = np.random.default_rng(8342310302941288912051)
457
+ ab = get_random((5, 4, 3, 6), dtype=dtype, rng=rng)
458
+ ab[..., -1, :] = 10 # make diagonal dominant
459
+ self.batch_test(linalg.cholesky_banded, ab)
460
+
461
+ @pytest.mark.parametrize('dtype', floating)
462
+ def test_block_diag(self, dtype):
463
+ rng = np.random.default_rng(8342310302941288912051)
464
+ a = get_random((1, 3, 1, 3), dtype=dtype, rng=rng)
465
+ b = get_random((2, 1, 3, 6), dtype=dtype, rng=rng)
466
+ c = get_random((1, 1, 3, 2), dtype=dtype, rng=rng)
467
+
468
+ # batch_test doesn't have the logic to broadcast just the batch shapes,
469
+ # so do it manually.
470
+ a2 = np.broadcast_to(a, (2, 3, 1, 3))
471
+ b2 = np.broadcast_to(b, (2, 3, 3, 6))
472
+ c2 = np.broadcast_to(c, (2, 3, 3, 2))
473
+ ref = self.batch_test(linalg.block_diag, (a2, b2, c2),
474
+ check_kwargs=False, broadcast=False)
475
+
476
+ # Check that `block_diag` broadcasts the batch shapes as expected.
477
+ res = linalg.block_diag(a, b, c)
478
+ assert_allclose(res, ref)
479
+
480
+ @pytest.mark.parametrize('fun_n_out', [(linalg.eigh_tridiagonal, 2),
481
+ (linalg.eigvalsh_tridiagonal, 1)])
482
+ @pytest.mark.parametrize('dtype', real_floating)
483
+ # "Only real arrays currently supported"
484
+ def test_eigh_tridiagonal(self, fun_n_out, dtype):
485
+ rng = np.random.default_rng(8342310302941288912051)
486
+ fun, n_out = fun_n_out
487
+ d = get_random((3, 4, 5), dtype=dtype, rng=rng)
488
+ e = get_random((3, 4, 4), dtype=dtype, rng=rng)
489
+ self.batch_test(fun, (d, e), core_dim=1, n_out=n_out, broadcast=False)
490
+
491
+ @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)])
492
+ @pytest.mark.parametrize('dtype', floating)
493
+ def test_solve(self, bdim, dtype):
494
+ rng = np.random.default_rng(8342310302941288912051)
495
+ A = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
496
+ b = get_random(bdim, dtype=dtype, rng=rng)
497
+ x = linalg.solve(A, b)
498
+ if len(bdim) == 1:
499
+ x = x[..., np.newaxis]
500
+ b = b[..., np.newaxis]
501
+ assert_allclose(A @ x - b, 0, atol=2e-6)
502
+ atol = 3e-6
503
+ if dtype is np.float32:
504
+ atol = 4e-6
505
+ assert_allclose(x, np.linalg.solve(A, b), atol=atol)
506
+
507
+ @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)])
508
+ @pytest.mark.parametrize('dtype', floating)
509
+ def test_lu_solve(self, bdim, dtype):
510
+ rng = np.random.default_rng(8342310302941288912051)
511
+ A = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
512
+ b = get_random(bdim, dtype=dtype, rng=rng)
513
+ lu_and_piv = linalg.lu_factor(A)
514
+ x = linalg.lu_solve(lu_and_piv, b)
515
+ if len(bdim) == 1:
516
+ x = x[..., np.newaxis]
517
+ b = b[..., np.newaxis]
518
+ assert_allclose(A @ x - b, 0, atol=2e-6)
519
+ atol = 3e-6
520
+ if dtype is np.float32:
521
+ atol = 4e-6
522
+ assert_allclose(x, np.linalg.solve(A, b), atol=atol)
523
+
524
+ @pytest.mark.parametrize('l_and_u', [(1, 1), ([2, 1, 0], [0, 1 , 2])])
525
+ @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)])
526
+ @pytest.mark.parametrize('dtype', floating)
527
+ def test_solve_banded(self, l_and_u, bdim, dtype):
528
+ rng = np.random.default_rng(8342310302941288912051)
529
+ l, u = l_and_u
530
+ ab = get_random((2, 3, 3, 5), dtype=dtype, rng=rng)
531
+ b = get_random(bdim, dtype=dtype, rng=rng)
532
+ x = linalg.solve_banded((l, u), ab, b)
533
+ for i in range(2):
534
+ for j in range(3):
535
+ bij = b if len(bdim) <= 2 else b[i, j]
536
+ lj = l if np.ndim(l) == 0 else l[j]
537
+ uj = u if np.ndim(u) == 0 else u[j]
538
+ xij = linalg.solve_banded((lj, uj), ab[i, j], bij)
539
+ assert_allclose(x[i, j], xij)
540
+
541
+ @pytest.mark.parametrize('separate_r', [False, True])
542
+ @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)])
543
+ @pytest.mark.parametrize('dtype', floating)
544
+ def test_solve_toeplitz(self, separate_r, bdim, dtype):
545
+ rng = np.random.default_rng(8342310302941288912051)
546
+ c = get_random((2, 3, 5), dtype=dtype, rng=rng)
547
+ r = get_random((2, 3, 5), dtype=dtype, rng=rng)
548
+ c_or_cr = (c, r) if separate_r else c
549
+ b = get_random(bdim, dtype=dtype, rng=rng)
550
+ x = linalg.solve_toeplitz(c_or_cr, b)
551
+ for i in range(2):
552
+ for j in range(3):
553
+ bij = b if len(bdim) <= 2 else b[i, j]
554
+ c_or_cr_ij = (c[i, j], r[i, j]) if separate_r else c[i, j]
555
+ xij = linalg.solve_toeplitz(c_or_cr_ij, bij)
556
+ assert_allclose(x[i, j], xij)
557
+
558
+ @pytest.mark.parametrize('separate_r', [False, True])
559
+ @pytest.mark.parametrize('xdim', [(5,), (5, 4), (2, 3, 5, 4)])
560
+ @pytest.mark.parametrize('dtype', floating)
561
+ def test_matmul_toeplitz(self, separate_r, xdim, dtype):
562
+ rng = np.random.default_rng(8342310302941288912051)
563
+ c = get_random((2, 3, 5), dtype=dtype, rng=rng)
564
+ r = get_random((2, 3, 5), dtype=dtype, rng=rng)
565
+ c_or_cr = (c, r) if separate_r else c
566
+ x = get_random(xdim, dtype=dtype, rng=rng)
567
+ res = linalg.matmul_toeplitz(c_or_cr, x)
568
+ if separate_r:
569
+ ref = linalg.toeplitz(c, r) @ x
570
+ else:
571
+ ref = linalg.toeplitz(c) @ x
572
+ atol = 1e-6 if dtype in {np.float32, np.complex64} else 1e-12
573
+ assert_allclose(res, ref, atol=atol)
574
+
575
+ @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)])
576
+ @pytest.mark.parametrize('dtype', floating)
577
+ def test_cho_solve(self, bdim, dtype):
578
+ rng = np.random.default_rng(8342310302941288912051)
579
+ A = get_nearly_hermitian((2, 3, 5, 5), dtype=dtype, atol=0, rng=rng)
580
+ A = A + 5*np.eye(5)
581
+ c_and_lower = linalg.cho_factor(A)
582
+ b = get_random(bdim, dtype=dtype, rng=rng)
583
+ x = linalg.cho_solve(c_and_lower, b)
584
+ if len(bdim) == 1:
585
+ x = x[..., np.newaxis]
586
+ b = b[..., np.newaxis]
587
+ assert_allclose(A @ x - b, 0, atol=1e-6)
588
+ assert_allclose(x, np.linalg.solve(A, b), atol=2e-6)
589
+
590
+ @pytest.mark.parametrize('lower', [False, True])
591
+ @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)])
592
+ @pytest.mark.parametrize('dtype', floating)
593
+ def test_cho_solve_banded(self, lower, bdim, dtype):
594
+ rng = np.random.default_rng(8342310302941288912051)
595
+ A = get_random((2, 3, 3, 5), dtype=dtype, rng=rng)
596
+ row_diag = 0 if lower else -1
597
+ A[:, :, row_diag] = 10
598
+ cb = linalg.cholesky_banded(A, lower=lower)
599
+ b = get_random(bdim, dtype=dtype, rng=rng)
600
+ x = linalg.cho_solve_banded((cb, lower), b)
601
+ for i in range(2):
602
+ for j in range(3):
603
+ bij = b if len(bdim) <= 2 else b[i, j]
604
+ xij = linalg.cho_solve_banded((cb[i, j], lower), bij)
605
+ assert_allclose(x[i, j], xij)
606
+
607
+ @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)])
608
+ @pytest.mark.parametrize('dtype', floating)
609
+ def test_solveh_banded(self, bdim, dtype):
610
+ rng = np.random.default_rng(8342310302941288912051)
611
+ A = get_random((2, 3, 3, 5), dtype=dtype, rng=rng)
612
+ A[:, :, -1] = 10
613
+ b = get_random(bdim, dtype=dtype, rng=rng)
614
+ x = linalg.solveh_banded(A, b)
615
+ for i in range(2):
616
+ for j in range(3):
617
+ bij = b if len(bdim) <= 2 else b[i, j]
618
+ xij = linalg.solveh_banded(A[i, j], bij)
619
+ assert_allclose(x[i, j], xij)
620
+
621
+ @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)])
622
+ @pytest.mark.parametrize('dtype', floating)
623
+ def test_solve_triangular(self, bdim, dtype):
624
+ rng = np.random.default_rng(8342310302941288912051)
625
+ A = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
626
+ A = np.tril(A)
627
+ b = get_random(bdim, dtype=dtype, rng=rng)
628
+ x = linalg.solve_triangular(A, b, lower=True)
629
+ if len(bdim) == 1:
630
+ x = x[..., np.newaxis]
631
+ b = b[..., np.newaxis]
632
+ atol = 1e-10 if dtype in (np.complex128, np.float64) else 2e-4
633
+ assert_allclose(A @ x - b, 0, atol=atol)
634
+ assert_allclose(x, np.linalg.solve(A, b), atol=5*atol)
635
+
636
+ @pytest.mark.parametrize('bdim', [(4,), (4, 3), (2, 3, 4, 3)])
637
+ @pytest.mark.parametrize('dtype', floating)
638
+ def test_lstsq(self, bdim, dtype):
639
+ rng = np.random.default_rng(8342310302941288912051)
640
+ A = get_random((2, 3, 4, 5), dtype=dtype, rng=rng)
641
+ b = get_random(bdim, dtype=dtype, rng=rng)
642
+ res = linalg.lstsq(A, b)
643
+ x = res[0]
644
+ if len(bdim) == 1:
645
+ x = x[..., np.newaxis]
646
+ b = b[..., np.newaxis]
647
+ assert_allclose(A @ x - b, 0, atol=2e-6)
648
+ assert len(res) == 4
649
+
650
+ @pytest.mark.parametrize('dtype', floating)
651
+ def test_clarkson_woodruff_transform(self, dtype):
652
+ rng = np.random.default_rng(8342310302941288912051)
653
+ A = get_random((5, 3, 4, 6), dtype=dtype, rng=rng)
654
+ self.batch_test(linalg.clarkson_woodruff_transform, A,
655
+ kwargs=dict(sketch_size=3, rng=311224))
656
+
657
+ def test_clarkson_woodruff_transform_sparse(self):
658
+ rng = np.random.default_rng(8342310302941288912051)
659
+ A = get_random((5, 3, 4, 6), dtype=np.float64, rng=rng)
660
+ A = sparse.coo_array(A)
661
+ message = "Batch support for sparse arrays is not available."
662
+ with pytest.raises(NotImplementedError, match=message):
663
+ linalg.clarkson_woodruff_transform(A, sketch_size=3, rng=rng)
664
+
665
+ @pytest.mark.parametrize('f, args', [
666
+ (linalg.toeplitz, (np.ones((0, 4)),)),
667
+ ])
668
+ def test_zero_size_batch(self, f, args):
669
+ message = "does not support zero-size batches."
670
+ with pytest.raises(ValueError, match=message):
671
+ f(*args)
672
+
673
+
674
+ @pytest.mark.parametrize(
675
+ "func, core_shape",
676
+ [
677
+ (linalg.solve, (3, 3)),
678
+ (linalg.solve_triangular, (3, 3)),
679
+ (lambda a, b: linalg.lstsq(a, b)[0], (3, 2)),
680
+ ],
681
+ ids=["solve", "solve_triangular", "lstsq",]
682
+ )
683
+ def test_shapes_solve_like(func, core_shape):
684
+ # test shapes for solve-like functions, where the 2nd argument may have trailing
685
+ # dimensions
686
+ m, n = core_shape
687
+
688
+ # ### 1. a.ndim == 2 ###
689
+
690
+ # 1.1 : b.ndim == 1, the "scalar" case
691
+ a = np.eye(m, n)
692
+ b = np.ones(m)
693
+
694
+ x = func(a, b)
695
+ assert x.shape == (n,)
696
+
697
+ # 1.2 : b.ndim == 2 : b has trailing dims
698
+ b = np.ones((m, 8))
699
+ x = func(a, b)
700
+ assert x.shape == (n, 8)
701
+
702
+ # 1.3 : b.ndim == 3 : b has trailing dims *and* batch dims
703
+ b = np.ones((4, m, 8))
704
+ x = func(a, b)
705
+ assert x.shape == (4, n, 8)
706
+
707
+ # 1.4 : b.ndim == 2 : b has batch dims *but* no trailing dims
708
+ b = np.ones((4, m))
709
+ pattern = "Shape mismatch|incompatible shapes|shapes of a|shape mismatch"
710
+ with pytest.raises(ValueError, match=pattern):
711
+ # fails to broadcast `b` vs `a` (to fix: append a length-1 trailing dim)
712
+ func(a, b)
713
+
714
+ # ### 2. a.ndim > 2 ###
715
+ a = np.broadcast_to(a, (5, 4, *a.shape)) # batch_shape = (5, 4)
716
+
717
+ # 2.1 : b is 1D
718
+ b = np.ones(m)
719
+ x = func(a, b)
720
+ assert x.shape == (5, 4, n)
721
+
722
+ # 2.2 : b.ndim == 2, has trailing dims
723
+ b = np.ones((m, 8))
724
+ x = func(a, b)
725
+ assert x.shape == (5, 4, n, 8)
726
+
727
+ # 2.3 : b has both trailing and batch dims
728
+ b = np.ones((5, 4, m, 8))
729
+ x = func(a, b)
730
+ assert x.shape == (5, 4, n, 8)
731
+
732
+ # 2.3.1 : b has trailing dims and (broadcastable) batch dims
733
+ b = np.ones((4, m, 8))
734
+ x = func(a, b)
735
+ assert x.shape == (5, 4, n, 8)
736
+
737
+ # 2.4 : b has batch dims but no trailing dims
738
+ b = np.ones((5, 4, m))
739
+ pattern = "Shape mismatch|incompatible shapes|shapes of a|shape mismatch"
740
+ with pytest.raises(ValueError, match=pattern):
741
+ # fails to broadcast `b` vs `a` (to fix: append a length-1 trailing dim)
742
+ func(a, b)
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_blas.py ADDED
@@ -0,0 +1,1133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Created by: Pearu Peterson, April 2002
3
+ #
4
+
5
+ import math
6
+ import pytest
7
+ import numpy as np
8
+ from numpy.testing import (assert_equal, assert_almost_equal,
9
+ assert_array_almost_equal, assert_allclose)
10
+ from pytest import raises as assert_raises
11
+
12
+ from numpy import (arange, triu, tril, zeros, tril_indices, ones,
13
+ diag, append, eye, nonzero)
14
+
15
+ import scipy
16
+ from scipy.linalg import get_blas_funcs, toeplitz, solve
17
+ from scipy.linalg.blas import HAS_ILP64
18
+
19
+ try:
20
+ from scipy.linalg import _fblas as fblas
21
+ FBLAS_ERROR = fblas.__fblas_error
22
+ HAS_LP64_FBLAS = True
23
+ except ImportError:
24
+ fblas = None
25
+ HAS_LP64_FBLAS = False
26
+
27
+ try:
28
+ from scipy.linalg import _fblas_64 as fblas_64
29
+ FBLAS_ERROR = fblas_64.__fblas_64_error
30
+ except ImportError:
31
+ fblas_64 = None
32
+
33
+
34
+ REAL_DTYPES = [np.float32, np.float64]
35
+ COMPLEX_DTYPES = [np.complex64, np.complex128]
36
+ DTYPES = REAL_DTYPES + COMPLEX_DTYPES
37
+
38
+
39
+ def test_get_blas_funcs():
40
+ # check that it returns Fortran code for arrays that are
41
+ # fortran-ordered
42
+ f1, f2, f3 = get_blas_funcs(
43
+ ('axpy', 'axpy', 'axpy'),
44
+ (np.empty((2, 2), dtype=np.complex64, order='F'),
45
+ np.empty((2, 2), dtype=np.complex128, order='C'))
46
+ )
47
+
48
+ # get_blas_funcs will choose libraries depending on most generic
49
+ # array
50
+ assert_equal(f1.typecode, 'z')
51
+ assert_equal(f2.typecode, 'z')
52
+
53
+ # check defaults.
54
+ f1 = get_blas_funcs('rotg')
55
+ assert_equal(f1.typecode, 'd')
56
+
57
+ # check also dtype interface
58
+ f1 = get_blas_funcs('gemm', dtype=np.complex64)
59
+ assert_equal(f1.typecode, 'c')
60
+ f1 = get_blas_funcs('gemm', dtype='F')
61
+ assert_equal(f1.typecode, 'c')
62
+
63
+ # extended precision complex
64
+ f1 = get_blas_funcs('gemm', dtype=np.clongdouble)
65
+ assert_equal(f1.typecode, 'z')
66
+
67
+ # check safe complex upcasting
68
+ f1 = get_blas_funcs('axpy',
69
+ (np.empty((2, 2), dtype=np.float64),
70
+ np.empty((2, 2), dtype=np.complex64))
71
+ )
72
+ assert_equal(f1.typecode, 'z')
73
+
74
+
75
+ def test_get_blas_funcs_ilp_preferred():
76
+ # "preferred" mean ILP64 if available LP64 otherwise
77
+ gemm = get_blas_funcs('gemm', (np.eye(3),), ilp64="preferred")
78
+ assert gemm.int_dtype == np.int64 if HAS_ILP64 else np.int32
79
+ assert gemm.module_name == 'fblas_64' if HAS_ILP64 else 'fblas'
80
+
81
+ # default is "preferred"
82
+ gemm = get_blas_funcs('gemm', (np.eye(3),))
83
+ assert gemm.int_dtype == np.int64 if HAS_ILP64 else np.int32
84
+ assert gemm.module_name == 'fblas_64' if HAS_ILP64 else 'fblas'
85
+
86
+
87
+ def test_get_blas_funcs_ilp_true():
88
+ # True is ILP64 or fail if not available
89
+ if HAS_ILP64:
90
+ gemm = get_blas_funcs('gemm', (np.eye(3),), ilp64=True)
91
+ assert gemm.int_dtype == np.int64
92
+ assert gemm.module_name == 'fblas_64'
93
+ else:
94
+ with pytest.raises(RuntimeError):
95
+ get_blas_funcs('gemm', (np.eye(3),), ilp64=True)
96
+
97
+
98
+ def test_get_blas_funcs_ilp_false():
99
+ # False is LP64 or fail if not available
100
+ if HAS_LP64_FBLAS:
101
+ gemm = get_blas_funcs('gemm', (np.eye(3),), ilp64=False)
102
+ assert gemm.int_dtype == np.int32
103
+ assert gemm.module_name == 'fblas'
104
+ else:
105
+ with pytest.raises(ValueError):
106
+ get_blas_funcs('gemm', (np.eye(3),), ilp64=False)
107
+
108
+
109
+ def test_get_blas_funcs_alias():
110
+ # check alias for get_blas_funcs
111
+ f, g = get_blas_funcs(('nrm2', 'dot'), dtype=np.complex64)
112
+ assert f.typecode == 'c'
113
+ assert g.typecode == 'c'
114
+
115
+ f, g, h = get_blas_funcs(('dot', 'dotc', 'dotu'), dtype=np.float64)
116
+ assert f is g
117
+ assert f is h
118
+
119
+
120
+ def _dt_from_prefix(prefix):
121
+ """Array dtype from a blas-style prefix."""
122
+ if prefix.startswith('i'):
123
+ prefix = prefix[1:] # isamax, idamax etc
124
+ elif prefix in ['sc', 'dz']:
125
+ prefix = prefix[0] # scasum, dzasum
126
+ elif prefix in ['cs', 'zd']:
127
+ prefix = prefix[0] # zdscal, csscal
128
+
129
+ dt_map = {'z': np.complex128, 'c': np.complex64, 'd': np.float64, 's': np.float32}
130
+ return dt_map[prefix]
131
+
132
+
133
+ def parametrize_blas(func_name, prefixes, modules=None):
134
+ """Parametrize a test over BLAS prefixes, "sdcz", and over the BLAS modules,
135
+ `fblas,fblas_64.
136
+
137
+ Given a func_name "gemm", this generates a pytest parametrization over up to 8
138
+ variants: sgemm, dgemm, cgemm, zgemm, each loaded from `fblas` (i.e. 32-bit LP64
139
+ variants) and `fblas_64` (i.e. 64-bit ILP64 variants)..
140
+
141
+ If a module is not available, the pytest parameter has a skip mark, so that the
142
+ test is skipped with a descriptive message.
143
+
144
+ Parameters
145
+ ----------
146
+ func_name : str
147
+ The base name of a BLAS function, e.g. "gemm"
148
+ prefixes : str or sequence
149
+ BLAS prefixes to prepend to `func_name`.
150
+ E.g. ``func_name='gemm', prefixes='cz'`` generates `cgemm` and `zgemm`.
151
+ modules : sequence of ``(module, str)`` pairs
152
+ BLAS modules to fetch functions from. By default, use `fblas` (LP64 variant)
153
+ and fblas_64 (ILP64 variant).
154
+ """
155
+ if modules is None:
156
+ modules = [(fblas, "fblas"), (fblas_64, "fblas_64")]
157
+
158
+ params = []
159
+ for mod, mod_name in modules:
160
+ for prefix in prefixes:
161
+ dtype = _dt_from_prefix(prefix)
162
+ if mod is None:
163
+ param_ = pytest.param(
164
+ None, dtype,
165
+ id=f"{mod_name}.{prefix}{func_name}",
166
+ marks=pytest.mark.skip(reason=f"{mod_name} is not available")
167
+ )
168
+ else:
169
+ # Fetch the BLAS function from the BLAS module. NB: if the name is not
170
+ # found in the module, it's a hard failure (all names must be present).
171
+ f = getattr(mod, prefix + func_name)
172
+ param_ = pytest.param(f, dtype, id=f"{mod_name}.{prefix}{func_name}")
173
+
174
+ params.append(param_)
175
+
176
+ return pytest.mark.parametrize("f, dtype", params)
177
+
178
+
179
+ class TestFBLAS1Simple:
180
+
181
+ @parametrize_blas("axpy", "sdcz")
182
+ def test_axpy(self, f, dtype):
183
+ assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5),
184
+ [7, 9, 18])
185
+ if dtype in COMPLEX_DTYPES:
186
+ assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5),
187
+ [7, 10j-1, 18])
188
+
189
+ @parametrize_blas("copy", "sdcz")
190
+ def test_copy(self, f, dtype):
191
+ assert_array_almost_equal(f([3, 4, 5], [8]*3), [3, 4, 5])
192
+ if dtype in COMPLEX_DTYPES:
193
+ assert_array_almost_equal(f([3, 4j, 5+3j], [8]*3), [3, 4j, 5+3j])
194
+
195
+ @parametrize_blas("asum", ["s", "d", "sc", "dz"])
196
+ def test_asum(self, f, dtype):
197
+ assert_almost_equal(f([3, -4, 5]), 12)
198
+ if dtype in COMPLEX_DTYPES:
199
+ assert_almost_equal(f([3j, -4, 3-4j]), 14)
200
+
201
+ @parametrize_blas("dot", "sd")
202
+ def test_dot(self, f, dtype):
203
+ assert_almost_equal(f([3, -4, 5], [2, 5, 1]), -9)
204
+
205
+ @parametrize_blas("dotu", "cz")
206
+ def test_dotu(self, f, dtype):
207
+ assert_almost_equal(f([3j, -4, 3-4j], [2, 3, 1]), -9+2j)
208
+
209
+ @parametrize_blas("dotc", "cz")
210
+ def test_dotc(self, f, dtype):
211
+ assert_almost_equal(f([3j, -4, 3-4j], [2, 3j, 1]), 3-14j)
212
+
213
+ @parametrize_blas("nrm2", ["s", "d", "sc", "dz"])
214
+ def test_nrm2(self, f, dtype):
215
+ assert_almost_equal(f([3, -4, 5]), math.sqrt(50))
216
+ if dtype in COMPLEX_DTYPES:
217
+ assert_almost_equal(f([3j, -4, 3-4j]), math.sqrt(50))
218
+
219
+ @parametrize_blas("scal", ["s", "d", "cs", "zd"])
220
+ def test_scal(self, f, dtype):
221
+ assert_array_almost_equal(f(2, [3, -4, 5]), [6, -8, 10])
222
+ if dtype in COMPLEX_DTYPES:
223
+ assert_array_almost_equal(f(3, [3j, -4, 3-4j]), [9j, -12, 9-12j])
224
+
225
+ @parametrize_blas("swap", "sdcz")
226
+ def test_swap(self, f, dtype):
227
+ x, y = [2, 3, 1], [-2, 3, 7]
228
+ x1, y1 = f(x, y)
229
+ assert_array_almost_equal(x1, y)
230
+ assert_array_almost_equal(y1, x)
231
+
232
+ if dtype in COMPLEX_DTYPES:
233
+ x, y = [2, 3j, 1], [-2, 3, 7-3j]
234
+ x1, y1 = f(x, y)
235
+ assert_array_almost_equal(x1, y)
236
+ assert_array_almost_equal(y1, x)
237
+
238
+ @parametrize_blas("amax", ["is", "id", "ic", "iz"])
239
+ def test_amax(self, f, dtype):
240
+ assert_equal(f([-2, 4, 3]), 1)
241
+ if dtype in COMPLEX_DTYPES:
242
+ assert_equal(f([-5, 4+3j, 6]), 1)
243
+
244
+ # XXX: need tests for rot,rotm,rotg,rotmg
245
+
246
+
247
+ class TestFBLAS2Simple:
248
+ @parametrize_blas("gemv", "sdcz")
249
+ def test_gemv(self, f, dtype):
250
+ assert_array_almost_equal(f(3, [[3]], [-4]), [-36])
251
+ assert_array_almost_equal(f(3, [[3]], [-4], 3, [5]), [-21])
252
+ if dtype in COMPLEX_DTYPES:
253
+ assert_array_almost_equal(f(3j, [[3-4j]], [-4]), [-48-36j])
254
+ assert_array_almost_equal(f(3j, [[3-4j]], [-4], 3, [5j]),
255
+ [-48-21j])
256
+
257
+ @parametrize_blas("ger", "sd")
258
+ def test_ger(self, f, dtype):
259
+ assert_array_almost_equal(f(1, [1, 2], [3, 4]), [[3, 4], [6, 8]])
260
+ assert_array_almost_equal(f(2, [1, 2, 3], [3, 4]),
261
+ [[6, 8], [12, 16], [18, 24]])
262
+ assert_array_almost_equal(f(1, [1, 2], [3, 4],
263
+ a=[[1, 2], [3, 4]]), [[4, 6], [9, 12]])
264
+ if dtype in COMPLEX_DTYPES:
265
+ assert_array_almost_equal(f(1, [1j, 2], [3, 4]),
266
+ [[3j, 4j], [6, 8]])
267
+ assert_array_almost_equal(f(2, [1j, 2j, 3j], [3j, 4j]),
268
+ [[6, 8], [12, 16], [18, 24]])
269
+
270
+ @parametrize_blas("geru", "cz")
271
+ def test_geru(self, f, dtype):
272
+ assert_array_almost_equal(f(1, [1j, 2], [3, 4]),
273
+ [[3j, 4j], [6, 8]])
274
+ assert_array_almost_equal(f(-2, [1j, 2j, 3j], [3j, 4j]),
275
+ [[6, 8], [12, 16], [18, 24]])
276
+
277
+ @parametrize_blas("gerc", "cz")
278
+ def test_gerc(self, f, dtype):
279
+ assert_array_almost_equal(f(1, [1j, 2], [3, 4]),
280
+ [[3j, 4j], [6, 8]])
281
+ assert_array_almost_equal(f(2, [1j, 2j, 3j], [3j, 4j]),
282
+ [[6, 8], [12, 16], [18, 24]])
283
+
284
+ @parametrize_blas("syr", "sdcz")
285
+ def test_syr(self, f, dtype):
286
+ x = np.arange(1, 5, dtype='d')
287
+ resx = np.triu(x[:, np.newaxis] * x)
288
+ resx_reverse = np.triu(x[::-1, np.newaxis] * x[::-1])
289
+ y = np.linspace(0, 8.5, 17, endpoint=False)
290
+ z = np.arange(1, 9, dtype='d').view('D')
291
+ resz = np.triu(z[:, np.newaxis] * z)
292
+ resz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1])
293
+ w = np.c_[np.zeros(4), z, np.zeros(4)].ravel()
294
+
295
+ rtol = np.finfo(dtype).eps
296
+
297
+ assert_allclose(f(1.0, x), resx, rtol=rtol)
298
+ assert_allclose(f(1.0, x, lower=True), resx.T, rtol=rtol)
299
+ assert_allclose(f(1.0, y, incx=2, offx=2, n=4), resx, rtol=rtol)
300
+ # negative increments imply reversed vectors in blas
301
+ assert_allclose(f(1.0, y, incx=-2, offx=2, n=4),
302
+ resx_reverse, rtol=rtol)
303
+
304
+ if dtype in COMPLEX_DTYPES:
305
+ assert_allclose(f(1.0, z), resz, rtol=rtol)
306
+ assert_allclose(f(1.0, z, lower=True), resz.T, rtol=rtol)
307
+ assert_allclose(f(1.0, w, incx=3, offx=1, n=4), resz, rtol=rtol)
308
+ # negative increments imply reversed vectors in blas
309
+ assert_allclose(f(1.0, w, incx=-3, offx=1, n=4),
310
+ resz_reverse, rtol=rtol)
311
+
312
+ a = np.zeros((4, 4), dtype, 'F')
313
+ b = f(1.0, z, a=a, overwrite_a=True)
314
+ assert_allclose(a, resz, rtol=rtol)
315
+ b = f(2.0, z, a=a)
316
+ assert a is not b
317
+ assert_allclose(b, 3*resz, rtol=rtol)
318
+
319
+ else:
320
+ a = np.zeros((4, 4), dtype, 'F')
321
+ b = f(1.0, x, a=a, overwrite_a=True)
322
+ assert_allclose(a, resx, rtol=rtol)
323
+ b = f(2.0, x, a=a)
324
+ assert a is not b
325
+ assert_allclose(b, 3*resx, rtol=rtol)
326
+
327
+ assert_raises(Exception, f, 1.0, x, incx=0)
328
+ assert_raises(Exception, f, 1.0, x, offx=5)
329
+ assert_raises(Exception, f, 1.0, x, offx=-2)
330
+ assert_raises(Exception, f, 1.0, x, n=-2)
331
+ assert_raises(Exception, f, 1.0, x, n=5)
332
+ assert_raises(Exception, f, 1.0, x, lower=2)
333
+ assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
334
+
335
+ @parametrize_blas("her", "cz")
336
+ def test_her(self, f, dtype):
337
+ x = np.arange(1, 5, dtype='d')
338
+ z = np.arange(1, 9, dtype='d').view('D')
339
+ rehz = np.triu(z[:, np.newaxis] * z.conj())
340
+ rehz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1].conj())
341
+ w = np.c_[np.zeros(4), z, np.zeros(4)].ravel()
342
+
343
+ rtol = np.finfo(dtype).eps
344
+
345
+ assert_allclose(f(1.0, z), rehz, rtol=rtol)
346
+ assert_allclose(f(1.0, z, lower=True), rehz.T.conj(), rtol=rtol)
347
+ assert_allclose(f(1.0, w, incx=3, offx=1, n=4), rehz, rtol=rtol)
348
+ # negative increments imply reversed vectors in blas
349
+ assert_allclose(f(1.0, w, incx=-3, offx=1, n=4),
350
+ rehz_reverse, rtol=rtol)
351
+
352
+ a = np.zeros((4, 4), dtype, 'F')
353
+ b = f(1.0, z, a=a, overwrite_a=True)
354
+ assert_allclose(a, rehz, rtol=rtol)
355
+
356
+ b = f(2.0, z, a=a)
357
+ assert a is not b
358
+ assert_allclose(b, 3*rehz, rtol=rtol)
359
+
360
+ assert_raises(Exception, f, 1.0, x, incx=0)
361
+ assert_raises(Exception, f, 1.0, x, offx=5)
362
+ assert_raises(Exception, f, 1.0, x, offx=-2)
363
+ assert_raises(Exception, f, 1.0, x, n=-2)
364
+ assert_raises(Exception, f, 1.0, x, n=5)
365
+ assert_raises(Exception, f, 1.0, x, lower=2)
366
+ assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
367
+
368
+ @parametrize_blas("syr2", "sd")
369
+ def test_syr2(self, f, dtype):
370
+ x = np.arange(1, 5, dtype='d')
371
+ y = np.arange(5, 9, dtype='d')
372
+ resxy = np.triu(x[:, np.newaxis] * y + y[:, np.newaxis] * x)
373
+ resxy_reverse = np.triu(x[::-1, np.newaxis] * y[::-1]
374
+ + y[::-1, np.newaxis] * x[::-1])
375
+
376
+ q = np.linspace(0, 8.5, 17, endpoint=False)
377
+ rtol = np.finfo(dtype).eps
378
+
379
+ assert_allclose(f(1.0, x, y), resxy, rtol=rtol)
380
+ assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol)
381
+ assert_allclose(f(1.0, x, y, lower=True), resxy.T, rtol=rtol)
382
+
383
+ assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10),
384
+ resxy, rtol=rtol)
385
+ assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10, n=3),
386
+ resxy[:3, :3], rtol=rtol)
387
+ # negative increments imply reversed vectors in blas
388
+ assert_allclose(f(1.0, q, q, incx=-2, offx=2, incy=-2, offy=10),
389
+ resxy_reverse, rtol=rtol)
390
+
391
+ a = np.zeros((4, 4), dtype, 'F')
392
+ b = f(1.0, x, y, a=a, overwrite_a=True)
393
+ assert_allclose(a, resxy, rtol=rtol)
394
+
395
+ b = f(2.0, x, y, a=a)
396
+ assert a is not b
397
+ assert_allclose(b, 3*resxy, rtol=rtol)
398
+
399
+ assert_raises(Exception, f, 1.0, x, y, incx=0)
400
+ assert_raises(Exception, f, 1.0, x, y, offx=5)
401
+ assert_raises(Exception, f, 1.0, x, y, offx=-2)
402
+ assert_raises(Exception, f, 1.0, x, y, incy=0)
403
+ assert_raises(Exception, f, 1.0, x, y, offy=5)
404
+ assert_raises(Exception, f, 1.0, x, y, offy=-2)
405
+ assert_raises(Exception, f, 1.0, x, y, n=-2)
406
+ assert_raises(Exception, f, 1.0, x, y, n=5)
407
+ assert_raises(Exception, f, 1.0, x, y, lower=2)
408
+ assert_raises(Exception, f, 1.0, x, y, a=np.zeros((2, 2), 'd', 'F'))
409
+
410
+ @parametrize_blas("her2", "cz")
411
+ def test_her2(self, f, dtype):
412
+ x = np.arange(1, 9, dtype='d').view('D')
413
+ y = np.arange(9, 17, dtype='d').view('D')
414
+ resxy = x[:, np.newaxis] * y.conj() + y[:, np.newaxis] * x.conj()
415
+ resxy = np.triu(resxy)
416
+
417
+ resxy_reverse = x[::-1, np.newaxis] * y[::-1].conj()
418
+ resxy_reverse += y[::-1, np.newaxis] * x[::-1].conj()
419
+ resxy_reverse = np.triu(resxy_reverse)
420
+
421
+ u = np.c_[np.zeros(4), x, np.zeros(4)].ravel()
422
+ v = np.c_[np.zeros(4), y, np.zeros(4)].ravel()
423
+
424
+ rtol = np.finfo(dtype).eps
425
+
426
+ assert_allclose(f(1.0, x, y), resxy, rtol=rtol)
427
+ assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol)
428
+ assert_allclose(f(1.0, x, y, lower=True), resxy.T.conj(),
429
+ rtol=rtol)
430
+
431
+ assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1),
432
+ resxy, rtol=rtol)
433
+ assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1, n=3),
434
+ resxy[:3, :3], rtol=rtol)
435
+ # negative increments imply reversed vectors in blas
436
+ assert_allclose(f(1.0, u, v, incx=-3, offx=1, incy=-3, offy=1),
437
+ resxy_reverse, rtol=rtol)
438
+
439
+ a = np.zeros((4, 4), dtype, 'F')
440
+ b = f(1.0, x, y, a=a, overwrite_a=True)
441
+ assert_allclose(a, resxy, rtol=rtol)
442
+
443
+ b = f(2.0, x, y, a=a)
444
+ assert a is not b
445
+ assert_allclose(b, 3*resxy, rtol=rtol)
446
+
447
+ assert_raises(Exception, f, 1.0, x, y, incx=0)
448
+ assert_raises(Exception, f, 1.0, x, y, offx=5)
449
+ assert_raises(Exception, f, 1.0, x, y, offx=-2)
450
+ assert_raises(Exception, f, 1.0, x, y, incy=0)
451
+ assert_raises(Exception, f, 1.0, x, y, offy=5)
452
+ assert_raises(Exception, f, 1.0, x, y, offy=-2)
453
+ assert_raises(Exception, f, 1.0, x, y, n=-2)
454
+ assert_raises(Exception, f, 1.0, x, y, n=5)
455
+ assert_raises(Exception, f, 1.0, x, y, lower=2)
456
+ assert_raises(Exception, f, 1.0, x, y,
457
+ a=np.zeros((2, 2), 'd', 'F'))
458
+
459
+ @parametrize_blas("gbmv", "sdcz")
460
+ def test_gbmv(self, f, dtype):
461
+ rng = np.random.default_rng(1234)
462
+ n = 7
463
+ m = 5
464
+ kl = 1
465
+ ku = 2
466
+ # fake a banded matrix via toeplitz
467
+ A = toeplitz(append(rng.random(kl+1), zeros(m-kl-1)),
468
+ append(rng.random(ku+1), zeros(n-ku-1)))
469
+ A = A.astype(dtype)
470
+ Ab = zeros((kl+ku+1, n), dtype=dtype)
471
+
472
+ # Form the banded storage
473
+ Ab[2, :5] = A[0, 0] # diag
474
+ Ab[1, 1:6] = A[0, 1] # sup1
475
+ Ab[0, 2:7] = A[0, 2] # sup2
476
+ Ab[3, :4] = A[1, 0] # sub1
477
+
478
+ x = rng.random(n).astype(dtype)
479
+ y = rng.random(m).astype(dtype)
480
+ alpha, beta = dtype(3), dtype(-5)
481
+
482
+ func = f
483
+ y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab,
484
+ x=x, y=y, beta=beta)
485
+ y2 = alpha * A.dot(x) + beta * y
486
+ assert_array_almost_equal(y1, y2)
487
+
488
+ y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab,
489
+ x=y, y=x, beta=beta, trans=1)
490
+ y2 = alpha * A.T.dot(y) + beta * x
491
+ assert_array_almost_equal(y1, y2)
492
+
493
+ @pytest.mark.parametrize("ilp64", [True, False])
494
+ @pytest.mark.parametrize("dtype", DTYPES)
495
+ def test_sbmv_hbmv(self, dtype, ilp64):
496
+ mod = fblas_64 if ilp64 else fblas
497
+ if mod is None:
498
+ mod_name = "fblas_64" if ilp64 else "fblas"
499
+ pytest.skip(f"{mod_name} is not available")
500
+
501
+ rng = np.random.default_rng(1234)
502
+ n = 6
503
+ k = 2
504
+ A = zeros((n, n), dtype=dtype)
505
+ Ab = zeros((k+1, n), dtype=dtype)
506
+
507
+ # Form the array and its packed banded storage
508
+ A[arange(n), arange(n)] = rng.random(n)
509
+ for ind2 in range(1, k+1):
510
+ temp = rng.random(n-ind2)
511
+ A[arange(n-ind2), arange(ind2, n)] = temp
512
+ Ab[-1-ind2, ind2:] = temp
513
+ A = A.astype(dtype)
514
+ if dtype in COMPLEX_DTYPES:
515
+ A += A.conj().T
516
+ func, = get_blas_funcs(('hbmv',), dtype=dtype, ilp64="preferred")
517
+ else:
518
+ A += A.T
519
+ func, = get_blas_funcs(('sbmv',), dtype=dtype, ilp64="preferred")
520
+
521
+ Ab[-1, :] = diag(A)
522
+ x = rng.random(n).astype(dtype)
523
+ y = rng.random(n).astype(dtype)
524
+ alpha, beta = dtype(1.25), dtype(3)
525
+
526
+ y1 = func(k=k, alpha=alpha, a=Ab, x=x, y=y, beta=beta)
527
+ y2 = alpha * A.dot(x) + beta * y
528
+ assert_array_almost_equal(y1, y2)
529
+
530
+ @pytest.mark.parametrize("ilp64", [True, False])
531
+ @pytest.mark.parametrize("fname,dtype", [
532
+ *[('spmv', dtype) for dtype in REAL_DTYPES + COMPLEX_DTYPES],
533
+ *[('hpmv', dtype) for dtype in COMPLEX_DTYPES],
534
+ ])
535
+ def test_spmv_hpmv(self, fname, dtype, ilp64):
536
+ mod = fblas_64 if ilp64 else fblas
537
+ if mod is None:
538
+ mod_name = "fblas_64" if ilp64 else "fblas"
539
+ pytest.skip(f"{mod_name} is not available")
540
+
541
+ rng = np.random.default_rng(1234)
542
+ n = 3
543
+ A = rng.random((n, n)).astype(dtype)
544
+ if dtype in COMPLEX_DTYPES:
545
+ A += rng.random((n, n))*1j
546
+ A += A.T if fname == 'spmv' else A.conj().T
547
+ c, r = tril_indices(n)
548
+ Ap = A[r, c]
549
+ x = rng.random(n).astype(dtype)
550
+ y = rng.random(n).astype(dtype)
551
+ xlong = arange(2*n).astype(dtype)
552
+ ylong = ones(2*n).astype(dtype)
553
+ alpha, beta = dtype(1.25), dtype(2)
554
+
555
+ func, = get_blas_funcs((fname,), dtype=dtype, ilp64="preferred")
556
+ y1 = func(n=n, alpha=alpha, ap=Ap, x=x, y=y, beta=beta)
557
+ y2 = alpha * A.dot(x) + beta * y
558
+ assert_array_almost_equal(y1, y2)
559
+
560
+ # Test inc and offsets
561
+ y1 = func(n=n-1, alpha=alpha, beta=beta, x=xlong, y=ylong, ap=Ap,
562
+ incx=2, incy=2, offx=n, offy=n)
563
+ y2 = (alpha * A[:-1, :-1]).dot(xlong[3::2]) + beta * ylong[3::2]
564
+ assert_array_almost_equal(y1[3::2], y2)
565
+ assert_almost_equal(y1[4], ylong[4])
566
+
567
+ @pytest.mark.parametrize("ilp64", [True, False])
568
+ @pytest.mark.parametrize("fname,dtype", [
569
+ *[('spr', dtype) for dtype in REAL_DTYPES + COMPLEX_DTYPES],
570
+ *[('hpr', dtype) for dtype in COMPLEX_DTYPES],
571
+ ])
572
+ def test_spr_hpr(self, fname, dtype, ilp64):
573
+ mod = fblas_64 if ilp64 else fblas
574
+ if mod is None:
575
+ mod_name = "fblas_64" if ilp64 else "fblas"
576
+ pytest.skip(f"{mod_name} is not available")
577
+
578
+ rng = np.random.default_rng(1234)
579
+ n = 3
580
+ A = rng.random((n, n)).astype(dtype)
581
+ if dtype in COMPLEX_DTYPES:
582
+ A += rng.random((n, n))*1j
583
+ A += A.T if fname == 'spr' else A.conj().T
584
+ c, r = tril_indices(n)
585
+ Ap = A[r, c]
586
+ x = rng.random(n).astype(dtype)
587
+
588
+ alpha = np.finfo(dtype).dtype.type(2.5)
589
+ if fname == 'hpr':
590
+ func, = get_blas_funcs(('hpr',), dtype=dtype, ilp64="preferred")
591
+ y2 = alpha * x[:, None].dot(x[None, :].conj()) + A
592
+ else:
593
+ func, = get_blas_funcs(('spr',), dtype=dtype, ilp64="preferred")
594
+ y2 = alpha * x[:, None].dot(x[None, :]) + A
595
+
596
+ y1 = func(n=n, alpha=alpha, ap=Ap, x=x)
597
+ y1f = zeros((3, 3), dtype=dtype)
598
+ y1f[r, c] = y1
599
+ y1f[c, r] = y1.conj() if fname == 'hpr' else y1
600
+ assert_array_almost_equal(y1f, y2)
601
+
602
+ @pytest.mark.parametrize("ilp64", [True, False])
603
+ @pytest.mark.parametrize("dtype", DTYPES)
604
+ def test_spr2_hpr2(self, dtype, ilp64):
605
+ mod = fblas_64 if ilp64 else fblas
606
+ if mod is None:
607
+ mod_name = "fblas_64" if ilp64 else "fblas"
608
+ pytest.skip(f"{mod_name} is not available")
609
+
610
+ rng = np.random.default_rng(1234)
611
+ n = 3
612
+ A = rng.random((n, n)).astype(dtype)
613
+ if dtype in COMPLEX_DTYPES:
614
+ A += rng.random((n, n))*1j
615
+ A += A.conj().T
616
+ func, = get_blas_funcs(('hpr2',), dtype=dtype, ilp64="preferred")
617
+ else:
618
+ A += A.T
619
+ func, = get_blas_funcs(('spr2',), dtype=dtype, ilp64="preferred")
620
+
621
+ c, r = tril_indices(n)
622
+ Ap = A[r, c]
623
+ x = rng.random(n).astype(dtype)
624
+ y = rng.random(n).astype(dtype)
625
+ alpha = dtype(2)
626
+
627
+ u = alpha.conj() * x[:, None].dot(y[None, :].conj())
628
+ y2 = A + u + u.conj().T
629
+ y1 = func(n=n, alpha=alpha, x=x, y=y, ap=Ap)
630
+ y1f = zeros((3, 3), dtype=dtype)
631
+ y1f[r, c] = y1
632
+ y1f[[1, 2, 2], [0, 0, 1]] = y1[[1, 3, 4]].conj()
633
+ assert_array_almost_equal(y1f, y2)
634
+
635
+ @parametrize_blas('tbmv', 'sdcz')
636
+ def test_tbmv(self, f, dtype):
637
+ rng = np.random.default_rng(1234)
638
+ n = 10
639
+ k = 3
640
+ x = rng.random(n).astype(dtype)
641
+ A = zeros((n, n), dtype=dtype)
642
+ # Banded upper triangular array
643
+ for sup in range(k+1):
644
+ A[arange(n-sup), arange(sup, n)] = rng.random(n-sup)
645
+
646
+ # Add complex parts for c,z
647
+ if dtype in COMPLEX_DTYPES:
648
+ A[nonzero(A)] += 1j * rng.random((k+1)*n-(k*(k+1)//2)).astype(dtype)
649
+
650
+ # Form the banded storage
651
+ Ab = zeros((k+1, n), dtype=dtype)
652
+ for row in range(k+1):
653
+ Ab[-row-1, row:] = diag(A, k=row)
654
+ func = f
655
+
656
+ y1 = func(k=k, a=Ab, x=x)
657
+ y2 = A.dot(x)
658
+ assert_array_almost_equal(y1, y2)
659
+
660
+ y1 = func(k=k, a=Ab, x=x, diag=1)
661
+ A[arange(n), arange(n)] = dtype(1)
662
+ y2 = A.dot(x)
663
+ assert_array_almost_equal(y1, y2)
664
+
665
+ y1 = func(k=k, a=Ab, x=x, diag=1, trans=1)
666
+ y2 = A.T.dot(x)
667
+ assert_array_almost_equal(y1, y2)
668
+
669
+ y1 = func(k=k, a=Ab, x=x, diag=1, trans=2)
670
+ y2 = A.conj().T.dot(x)
671
+ assert_array_almost_equal(y1, y2)
672
+
673
+ @parametrize_blas('tbsv', 'sdcz')
674
+ def test_tbsv(self, f, dtype):
675
+ rng = np.random.default_rng(12345)
676
+ n = 6
677
+ k = 3
678
+ x = rng.random(n).astype(dtype)
679
+ A = zeros((n, n), dtype=dtype)
680
+ # Banded upper triangular array
681
+ for sup in range(k+1):
682
+ A[arange(n-sup), arange(sup, n)] = rng.random(n-sup)
683
+
684
+ # Add complex parts for c,z
685
+ if dtype in COMPLEX_DTYPES:
686
+ A[nonzero(A)] += 1j * rng.random((k+1)*n-(k*(k+1)//2)).astype(dtype)
687
+
688
+ # Form the banded storage
689
+ Ab = zeros((k+1, n), dtype=dtype)
690
+ for row in range(k+1):
691
+ Ab[-row-1, row:] = diag(A, k=row)
692
+ func = f
693
+
694
+ y1 = func(k=k, a=Ab, x=x)
695
+ y2 = solve(A, x)
696
+ assert_array_almost_equal(y1, y2)
697
+
698
+ y1 = func(k=k, a=Ab, x=x, diag=1)
699
+ A[arange(n), arange(n)] = dtype(1)
700
+ y2 = solve(A, x)
701
+ assert_array_almost_equal(y1, y2)
702
+
703
+ y1 = func(k=k, a=Ab, x=x, diag=1, trans=1)
704
+ y2 = solve(A.T, x)
705
+ assert_array_almost_equal(y1, y2)
706
+
707
+ y1 = func(k=k, a=Ab, x=x, diag=1, trans=2)
708
+ y2 = solve(A.conj().T, x)
709
+ assert_array_almost_equal(y1, y2)
710
+
711
+ @parametrize_blas('tpmv', 'sdcz')
712
+ def test_tpmv(self, f, dtype):
713
+ rng = np.random.default_rng(1234)
714
+ n = 10
715
+ x = rng.random(n).astype(dtype)
716
+ # Upper triangular array
717
+ if dtype in COMPLEX_DTYPES:
718
+ A = triu(rng.random((n, n)) + rng.random((n, n))*1j)
719
+ else:
720
+ A = triu(rng.random((n, n)))
721
+
722
+ # Form the packed storage
723
+ c, r = tril_indices(n)
724
+ Ap = A[r, c]
725
+ func = f
726
+
727
+ y1 = func(n=n, ap=Ap, x=x)
728
+ y2 = A.dot(x)
729
+ assert_array_almost_equal(y1, y2)
730
+
731
+ y1 = func(n=n, ap=Ap, x=x, diag=1)
732
+ A[arange(n), arange(n)] = dtype(1)
733
+ y2 = A.dot(x)
734
+ assert_array_almost_equal(y1, y2)
735
+
736
+ y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1)
737
+ y2 = A.T.dot(x)
738
+ assert_array_almost_equal(y1, y2)
739
+
740
+ y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2)
741
+ y2 = A.conj().T.dot(x)
742
+ assert_array_almost_equal(y1, y2)
743
+
744
+ @parametrize_blas('tpsv', 'sdcz')
745
+ def test_tpsv(self, f, dtype):
746
+ rng = np.random.default_rng(1234)
747
+ n = 10
748
+ x = rng.random(n).astype(dtype)
749
+ # Upper triangular array
750
+ if dtype in COMPLEX_DTYPES:
751
+ A = triu(rng.random((n, n)) + rng.random((n, n))*1j)
752
+ else:
753
+ A = triu(rng.random((n, n)))
754
+ A += eye(n)
755
+ # Form the packed storage
756
+ c, r = tril_indices(n)
757
+ Ap = A[r, c]
758
+ func = f
759
+
760
+ y1 = func(n=n, ap=Ap, x=x)
761
+ y2 = solve(A, x)
762
+ assert_array_almost_equal(y1, y2)
763
+
764
+ y1 = func(n=n, ap=Ap, x=x, diag=1)
765
+ A[arange(n), arange(n)] = dtype(1)
766
+ y2 = solve(A, x)
767
+ assert_array_almost_equal(y1, y2)
768
+
769
+ y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1)
770
+ y2 = solve(A.T, x)
771
+ assert_array_almost_equal(y1, y2)
772
+
773
+ y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2)
774
+ y2 = solve(A.conj().T, x)
775
+ assert_array_almost_equal(y1, y2)
776
+
777
+ @parametrize_blas('trmv', 'sdcz')
778
+ def test_trmv(self, f, dtype):
779
+ rng = np.random.default_rng(1234)
780
+ n = 3
781
+ A = (rng.random((n, n))+eye(n)).astype(dtype)
782
+ x = rng.random(3).astype(dtype)
783
+ func = f
784
+
785
+ y1 = func(a=A, x=x)
786
+ y2 = triu(A).dot(x)
787
+ assert_array_almost_equal(y1, y2)
788
+
789
+ y1 = func(a=A, x=x, diag=1)
790
+ A[arange(n), arange(n)] = dtype(1)
791
+ y2 = triu(A).dot(x)
792
+ assert_array_almost_equal(y1, y2)
793
+
794
+ y1 = func(a=A, x=x, diag=1, trans=1)
795
+ y2 = triu(A).T.dot(x)
796
+ assert_array_almost_equal(y1, y2)
797
+
798
+ y1 = func(a=A, x=x, diag=1, trans=2)
799
+ y2 = triu(A).conj().T.dot(x)
800
+ assert_array_almost_equal(y1, y2)
801
+
802
+ @parametrize_blas('trsv', 'sdcz')
803
+ def test_trsv(self, f, dtype):
804
+ rng = np.random.default_rng(1234)
805
+ n = 15
806
+ A = (rng.random((n, n))+eye(n)).astype(dtype)
807
+ x = rng.random(n).astype(dtype)
808
+ func = f
809
+
810
+ y1 = func(a=A, x=x)
811
+ y2 = solve(triu(A), x)
812
+ assert_array_almost_equal(y1, y2)
813
+
814
+ y1 = func(a=A, x=x, lower=1)
815
+ y2 = solve(tril(A), x)
816
+ assert_array_almost_equal(y1, y2)
817
+
818
+ y1 = func(a=A, x=x, diag=1)
819
+ A[arange(n), arange(n)] = dtype(1)
820
+ y2 = solve(triu(A), x)
821
+ assert_array_almost_equal(y1, y2)
822
+
823
+ y1 = func(a=A, x=x, diag=1, trans=1)
824
+ y2 = solve(triu(A).T, x)
825
+ assert_array_almost_equal(y1, y2)
826
+
827
+ y1 = func(a=A, x=x, diag=1, trans=2)
828
+ y2 = solve(triu(A).conj().T, x)
829
+ assert_array_almost_equal(y1, y2)
830
+
831
+
832
+ class TestFBLAS3Simple:
833
+ @parametrize_blas("gemm", "sdcz")
834
+ def test_gemm(self, f, dtype):
835
+ assert_array_almost_equal(f(3, [3], [-4]), [[-36]])
836
+ assert_array_almost_equal(f(3, [3], [-4], 3, [5]), [-21])
837
+ if dtype in COMPLEX_DTYPES:
838
+ assert_array_almost_equal(f(3j, [3-4j], [-4]), [[-48-36j]])
839
+ assert_array_almost_equal(f(3j, [3-4j], [-4], 3, [5j]), [-48-21j])
840
+
841
+
842
+ class TestBLAS3Symm:
843
+
844
+ def setup_method(self):
845
+ self.a = np.array([[1., 2.],
846
+ [0., 1.]])
847
+ self.b = np.array([[1., 0., 3.],
848
+ [0., -1., 2.]])
849
+ self.c = np.ones((2, 3))
850
+ self.t = np.array([[2., -1., 8.],
851
+ [3., 0., 9.]])
852
+
853
+ @parametrize_blas("symm", "sdcz")
854
+ def test_symm(self, f, dtype):
855
+ res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.)
856
+ assert_array_almost_equal(res, self.t)
857
+
858
+ res = f(a=self.a.T, b=self.b, lower=1, c=self.c, alpha=1., beta=1.)
859
+ assert_array_almost_equal(res, self.t)
860
+
861
+ res = f(a=self.a, b=self.b.T, side=1, c=self.c.T,
862
+ alpha=1., beta=1.)
863
+ assert_array_almost_equal(res, self.t.T)
864
+
865
+ @parametrize_blas("symm", "sdcz")
866
+ def test_symm_wrong_side(self, f, dtype):
867
+ """`side=1` means C <- B*A, hence shapes of A and B are to be
868
+ compatible. Otherwise, f2py exception is raised.
869
+ """
870
+ # FIXME narrow down to _fblas.error
871
+ with pytest.raises(Exception):
872
+ f(a=self.a, b=self.b, alpha=1, side=1)
873
+
874
+ @parametrize_blas("symm", "sdcz")
875
+ def test_symm_wrong_uplo(self, f, dtype):
876
+ """SYMM only considers the upper/lower part of A. Hence setting
877
+ wrong value for `lower` (default is lower=0, meaning upper triangle)
878
+ gives a wrong result.
879
+ """
880
+ res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.)
881
+ assert np.allclose(res, self.t)
882
+ res = f(a=self.a, b=self.b, lower=1, c=self.c, alpha=1., beta=1.)
883
+ assert not np.allclose(res, self.t)
884
+
885
+
886
+ class TestBLAS3Syrk:
887
+ def setup_method(self):
888
+ self.a = np.array([[1., 0.],
889
+ [0., -2.],
890
+ [2., 3.]])
891
+ self.t = np.array([[1., 0., 2.],
892
+ [0., 4., -6.],
893
+ [2., -6., 13.]])
894
+ self.tt = np.array([[5., 6.],
895
+ [6., 13.]])
896
+
897
+ @parametrize_blas("syrk", "sdcz")
898
+ def test_syrk(self, f, dtype):
899
+ c = f(a=self.a, alpha=1.)
900
+ assert_array_almost_equal(np.triu(c), np.triu(self.t))
901
+
902
+ c = f(a=self.a, alpha=1., lower=1)
903
+ assert_array_almost_equal(np.tril(c), np.tril(self.t))
904
+
905
+ c0 = np.ones(self.t.shape)
906
+ c = f(a=self.a, alpha=1., beta=1., c=c0)
907
+ assert_array_almost_equal(np.triu(c), np.triu(self.t+c0))
908
+
909
+ c = f(a=self.a, alpha=1., trans=1)
910
+ assert_array_almost_equal(np.triu(c), np.triu(self.tt))
911
+
912
+ # prints '0-th dimension must be fixed to 3 but got 5',
913
+ # FIXME: suppress?
914
+ @parametrize_blas("syrk", "sdcz")
915
+ def test_syrk_wrong_c(self, f, dtype):
916
+ # FIXME narrow down to _fblas.error
917
+ with pytest.raises(Exception):
918
+ f(a=self.a, alpha=1., c=np.ones((5, 8)))
919
+ # if C is supplied, it must have compatible dimensions
920
+
921
+
922
+ class TestBLAS3Syr2k:
923
+ def setup_method(self):
924
+ self.a = np.array([[1., 0.],
925
+ [0., -2.],
926
+ [2., 3.]])
927
+ self.b = np.array([[0., 1.],
928
+ [1., 0.],
929
+ [0, 1.]])
930
+ self.t = np.array([[0., -1., 3.],
931
+ [-1., 0., 0.],
932
+ [3., 0., 6.]])
933
+ self.tt = np.array([[0., 1.],
934
+ [1., 6]])
935
+
936
+ @parametrize_blas("syr2k", "sdcz")
937
+ def test_syr2k(self, f, dtype):
938
+ c = f(a=self.a, b=self.b, alpha=1.)
939
+ assert_array_almost_equal(np.triu(c), np.triu(self.t))
940
+
941
+ c = f(a=self.a, b=self.b, alpha=1., lower=1)
942
+ assert_array_almost_equal(np.tril(c), np.tril(self.t))
943
+
944
+ c0 = np.ones(self.t.shape)
945
+ c = f(a=self.a, b=self.b, alpha=1., beta=1., c=c0)
946
+ assert_array_almost_equal(np.triu(c), np.triu(self.t+c0))
947
+
948
+ c = f(a=self.a, b=self.b, alpha=1., trans=1)
949
+ assert_array_almost_equal(np.triu(c), np.triu(self.tt))
950
+
951
+ # prints '0-th dimension must be fixed to 3 but got 5', FIXME: suppress?
952
+ @parametrize_blas("syr2k", "sdcz")
953
+ def test_syr2k_wrong_c(self, f, dtype):
954
+ with pytest.raises(Exception):
955
+ f(a=self.a, b=self.b, alpha=1., c=np.zeros((15, 8)))
956
+ # if C is supplied, it must have compatible dimensions
957
+
958
+
959
+ class TestSyHe:
960
+ """Quick and simple tests for (zc)-symm, syrk, syr2k."""
961
+
962
+ def setup_method(self):
963
+ self.sigma_y = np.array([[0., -1.j],
964
+ [1.j, 0.]])
965
+
966
+ @parametrize_blas("symm", "zc")
967
+ def test_symm(self, f, dtype):
968
+ # NB: a is symmetric w/upper diag of ONLY
969
+ res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
970
+ assert_array_almost_equal(np.triu(res), np.diag([1, -1]))
971
+
972
+ @parametrize_blas("hemm", "zc")
973
+ def test_hemm(self, f, dtype):
974
+ # NB: a is hermitian w/upper diag of ONLY
975
+ res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
976
+ assert_array_almost_equal(np.triu(res), np.diag([1, 1]))
977
+
978
+ @parametrize_blas("syrk", "zc")
979
+ def test_syrk(self, f, dtype):
980
+ res = f(a=self.sigma_y, alpha=1.)
981
+ assert_array_almost_equal(np.triu(res), np.diag([-1, -1]))
982
+
983
+ @parametrize_blas("herk", "zc")
984
+ def test_herk(self, f, dtype):
985
+ res = f(a=self.sigma_y, alpha=1.)
986
+ assert_array_almost_equal(np.triu(res), np.diag([1, 1]))
987
+
988
+ @parametrize_blas("syr2k", "zc")
989
+ def test_syr2k_zr(self, f, dtype):
990
+ res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
991
+ assert_array_almost_equal(np.triu(res), 2.*np.diag([-1, -1]))
992
+
993
+ @parametrize_blas("her2k", "zc")
994
+ def test_her2k_zr(self, f, dtype):
995
+ res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
996
+ assert_array_almost_equal(np.triu(res), 2.*np.diag([1, 1]))
997
+
998
+
999
+ class TestTRMM:
1000
+ """Quick and simple tests for *trmm."""
1001
+
1002
+ def setup_method(self):
1003
+ self.a = np.array([[1., 2., ],
1004
+ [-2., 1.]])
1005
+ self.b = np.array([[3., 4., -1.],
1006
+ [5., 6., -2.]])
1007
+
1008
+ self.a2 = np.array([[1, 1, 2, 3],
1009
+ [0, 1, 4, 5],
1010
+ [0, 0, 1, 6],
1011
+ [0, 0, 0, 1]], order="f")
1012
+ self.b2 = np.array([[1, 4], [2, 5], [3, 6], [7, 8], [9, 10]],
1013
+ order="f")
1014
+
1015
+ @parametrize_blas("trmm", "sdzc")
1016
+ def test_side(self, f, dtype):
1017
+ trmm = f
1018
+ # Provide large A array that works for side=1 but not 0 (see gh-10841)
1019
+ assert_raises(Exception, trmm, 1.0, self.a2, self.b2)
1020
+ res = trmm(1.0, self.a2.astype(dtype), self.b2.astype(dtype),
1021
+ side=1)
1022
+ k = self.b2.shape[1]
1023
+ assert_allclose(res, self.b2 @ self.a2[:k, :k], rtol=0.,
1024
+ atol=100*np.finfo(dtype).eps)
1025
+
1026
+ @parametrize_blas("trmm", "sdcz")
1027
+ def test_ab(self, f, dtype):
1028
+ result = f(1., self.a, self.b)
1029
+ # default a is upper triangular
1030
+ expected = np.array([[13., 16., -5.],
1031
+ [ 5., 6., -2.]])
1032
+ assert_array_almost_equal(result, expected)
1033
+
1034
+ @parametrize_blas("trmm", "sdcz")
1035
+ def test_ab_lower(self, f, dtype):
1036
+ result = f(1., self.a, self.b, lower=True)
1037
+ expected = np.array([[ 3., 4., -1.],
1038
+ [-1., -2., 0.]]) # now a is lower triangular
1039
+ assert_array_almost_equal(result, expected)
1040
+
1041
+ @parametrize_blas("trmm", "sdcz")
1042
+ def test_b_overwrites(self, f, dtype):
1043
+ # BLAS *trmm modifies B argument in-place.
1044
+ # Here the default is to copy, but this can be overridden
1045
+ b = self.b.astype(dtype)
1046
+ for overwr in [True, False]:
1047
+ bcopy = b.copy()
1048
+ result = f(1., self.a, bcopy, overwrite_b=overwr)
1049
+ # C-contiguous arrays are copied
1050
+ assert not bcopy.flags.f_contiguous
1051
+ assert not np.may_share_memory(bcopy, result)
1052
+ assert_equal(bcopy, b)
1053
+
1054
+ bcopy = np.asfortranarray(b.copy()) # or just transpose it
1055
+ result = f(1., self.a, bcopy, overwrite_b=True)
1056
+ assert bcopy.flags.f_contiguous
1057
+ assert np.may_share_memory(bcopy, result)
1058
+ assert_array_almost_equal(bcopy, result)
1059
+
1060
+
1061
+ @parametrize_blas("trsm", "sdcz")
1062
+ def test_trsm(f, dtype):
1063
+ rng = np.random.default_rng(1234)
1064
+ tol = np.finfo(dtype).eps*1000
1065
+ func = f
1066
+
1067
+ # Test protection against size mismatches
1068
+ A = rng.random((4, 5)).astype(dtype)
1069
+ B = rng.random((4, 4)).astype(dtype)
1070
+ alpha = dtype(1)
1071
+ assert_raises(Exception, func, alpha, A, B)
1072
+ assert_raises(Exception, func, alpha, A.T, B)
1073
+
1074
+ n = 8
1075
+ m = 7
1076
+ alpha = dtype(-2.5)
1077
+ if dtype in COMPLEX_DTYPES:
1078
+ A = (rng.random((m, m)) + rng.random((m, m))*1j) + eye(m)
1079
+ else:
1080
+ A = rng.random((m, m)) + eye(m)
1081
+ A = A.astype(dtype)
1082
+ Au = triu(A)
1083
+ Al = tril(A)
1084
+ B1 = rng.random((m, n)).astype(dtype)
1085
+ B2 = rng.random((n, m)).astype(dtype)
1086
+
1087
+ x1 = func(alpha=alpha, a=A, b=B1)
1088
+ assert_equal(B1.shape, x1.shape)
1089
+ x2 = solve(Au, alpha*B1)
1090
+ assert_allclose(x1, x2, atol=tol)
1091
+
1092
+ x1 = func(alpha=alpha, a=A, b=B1, trans_a=1)
1093
+ x2 = solve(Au.T, alpha*B1)
1094
+ assert_allclose(x1, x2, atol=tol)
1095
+
1096
+ x1 = func(alpha=alpha, a=A, b=B1, trans_a=2)
1097
+ x2 = solve(Au.conj().T, alpha*B1)
1098
+ assert_allclose(x1, x2, atol=tol)
1099
+
1100
+ x1 = func(alpha=alpha, a=A, b=B1, diag=1)
1101
+ Au[arange(m), arange(m)] = dtype(1)
1102
+ x2 = solve(Au, alpha*B1)
1103
+ assert_allclose(x1, x2, atol=tol)
1104
+
1105
+ x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1)
1106
+ x2 = solve(Au.conj().T, alpha*B2.conj().T)
1107
+ assert_allclose(x1, x2.conj().T, atol=tol)
1108
+
1109
+ x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1, lower=1)
1110
+ Al[arange(m), arange(m)] = dtype(1)
1111
+ x2 = solve(Al.conj().T, alpha*B2.conj().T)
1112
+ assert_allclose(x1, x2.conj().T, atol=tol)
1113
+
1114
+
1115
+ @pytest.mark.xfail(run=False,
1116
+ reason="gh-16930")
1117
+ def test_gh_169309():
1118
+ x = np.repeat(10, 9)
1119
+ actual = scipy.linalg.blas.dnrm2(x, 5, 3, -1)
1120
+ expected = math.sqrt(500)
1121
+ assert_allclose(actual, expected)
1122
+
1123
+
1124
+ @pytest.mark.xfail(HAS_ILP64, reason='does not fail with ILP64 MKL')
1125
+ def test_dnrm2_neg_incx():
1126
+ # check that dnrm2(..., incx < 0) raises
1127
+ # XXX: remove the test after the lowest supported BLAS implements
1128
+ # negative incx (new in LAPACK 3.10)
1129
+ x = np.repeat(10, 9)
1130
+ incx = -1
1131
+ dnrm2 = scipy.linalg.blas.get_blas_funcs('nrm2', (x,), ilp64='preferred')
1132
+ with assert_raises(FBLAS_ERROR):
1133
+ dnrm2(x, 5, 3, incx)
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cython_abi.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ---------------------------------------------------------------------------
2
+ # AUTO-GENERATED - do not edit by hand.
3
+ # Re-generate with: python tools/generate_cython_abi_tests.py linalg
4
+ #
5
+ # Generated against SciPy 1.17.1 on 2026-03-29
6
+ # Python 3.12.13
7
+ # ---------------------------------------------------------------------------
8
+
9
+ """
10
+ Regression test for the cython_blas / cython_lapack binary interface.
11
+
12
+ The __pyx_capi__ dict of each module contains PyCapsule objects whose
13
+ *name* string encodes the C-level function signature that Cython checks
14
+ at import time when another module does ``cimport``. Any change to
15
+ those strings is a binary incompatibility that breaks every downstream
16
+ package (e.g., scikit-learn, statsmodels) compiled against the previous release,
17
+ without any compile-time warning.
18
+
19
+ The expected signatures are stored in cython_abi_signatures.json.
20
+ The test fails if:
21
+ * an existing name disappears, or
22
+ * an existing name's signature string changes.
23
+ Adding new names is explicitly allowed (it is not a break).
24
+ """
25
+
26
+ import ctypes
27
+ import importlib
28
+ import importlib.resources
29
+ import json
30
+
31
+ import pytest
32
+ import scipy
33
+
34
+ CYTHON_BLAS_ILP64 = (
35
+ scipy.show_config(mode='dicts')['Build Dependencies']['blas']['cython blas ilp64']
36
+ )
37
+
38
+
39
+ # ---------------------------------------------------------------------------
40
+ # Helper
41
+ # ---------------------------------------------------------------------------
42
+
43
+ _get_capsule_name = ctypes.pythonapi.PyCapsule_GetName
44
+ _get_capsule_name.restype = ctypes.c_char_p
45
+ _get_capsule_name.argtypes = [ctypes.py_object]
46
+
47
+
48
+ def _extract_capi(module):
49
+ """Return {name: signature} for every entry in module.__pyx_capi__."""
50
+ result = {}
51
+ for name, capsule in module.__pyx_capi__.items():
52
+ raw = _get_capsule_name(capsule)
53
+ if raw is not None:
54
+ result[name] = raw.decode('utf-8')
55
+ return result
56
+
57
+
58
+ _sig_file = importlib.resources.files('scipy.linalg.tests').joinpath(
59
+ 'cython_abi_signatures.json'
60
+ )
61
+ with importlib.resources.as_file(_sig_file) as _f:
62
+ _EXPECTED = json.loads(_f.read_text())
63
+
64
+
65
+ @pytest.mark.skipif(
66
+ CYTHON_BLAS_ILP64,
67
+ reason='cython_blas/cython_lapack ABI depends on ILP64 BLAS',
68
+ )
69
+ def test_cython_blas_abi_stability():
70
+ """No existing cython_blas signature may change or disappear."""
71
+ expected = _EXPECTED['scipy.linalg.cython_blas']
72
+ mod = importlib.import_module('scipy.linalg.cython_blas')
73
+ actual = _extract_capi(mod)
74
+ errors = []
75
+ for name, expected_sig in expected.items():
76
+ if name not in actual:
77
+ errors.append(
78
+ f"REMOVED {name!r} (was {expected_sig!r})"
79
+ )
80
+ elif actual[name] != expected_sig:
81
+ errors.append(
82
+ f"CHANGED {name!r}\n"
83
+ f" expected: {expected_sig!r}\n"
84
+ f" actual: {actual[name]!r}"
85
+ )
86
+ if errors:
87
+ joined = '\n'.join(errors)
88
+ pytest.fail(
89
+ f"scipy.linalg.cython_blas.__pyx_capi__ has {len(errors)} "
90
+ f"ABI breakage(s):\n{joined}"
91
+ )
92
+
93
+
94
+ @pytest.mark.skipif(
95
+ CYTHON_BLAS_ILP64,
96
+ reason='cython_blas/cython_lapack ABI depends on ILP64 BLAS',
97
+ )
98
+ def test_cython_lapack_abi_stability():
99
+ """No existing cython_lapack signature may change or disappear."""
100
+ expected = _EXPECTED['scipy.linalg.cython_lapack']
101
+ mod = importlib.import_module('scipy.linalg.cython_lapack')
102
+ actual = _extract_capi(mod)
103
+ errors = []
104
+ for name, expected_sig in expected.items():
105
+ if name not in actual:
106
+ errors.append(
107
+ f"REMOVED {name!r} (was {expected_sig!r})"
108
+ )
109
+ elif actual[name] != expected_sig:
110
+ errors.append(
111
+ f"CHANGED {name!r}\n"
112
+ f" expected: {expected_sig!r}\n"
113
+ f" actual: {actual[name]!r}"
114
+ )
115
+ if errors:
116
+ joined = '\n'.join(errors)
117
+ pytest.fail(
118
+ f"scipy.linalg.cython_lapack.__pyx_capi__ has {len(errors)} "
119
+ f"ABI breakage(s):\n{joined}"
120
+ )
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cython_blas.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy.testing import (assert_allclose,
3
+ assert_equal)
4
+ import scipy.linalg.cython_blas as blas
5
+
6
+
7
+ class TestBlasInt:
8
+ """Tests for blas_int type used in cython_blas/cython_lapack."""
9
+
10
+ def test_blas_int_size(self):
11
+ """Verify blas_int size matches the build configuration."""
12
+ from scipy.__config__ import CONFIG
13
+ size = blas._blas_int_size()
14
+ cython_blas_ilp64 = CONFIG['Build Dependencies']['blas']['cython blas ilp64']
15
+ if cython_blas_ilp64:
16
+ assert size == 8, f"ILP64 build but blas_int is {size} bytes"
17
+ else:
18
+ assert size == 4, f"LP64 build but blas_int is {size} bytes"
19
+
20
+ # also verify blas_bint size
21
+ bint_sizes = blas._blas_bint_bint_sizes() # (sizeof(blas_bint), sizeof(bint))
22
+ if cython_blas_ilp64:
23
+ assert bint_sizes == (8, 4)
24
+ else:
25
+ assert bint_sizes == (4, 4)
26
+
27
+ def test_dgemm_with_blas_int_dimensions(self):
28
+ """Test dgemm works correctly - exercises blas_int for dimensions."""
29
+ a = np.eye(3, dtype=np.float64)
30
+ b = np.arange(9, dtype=np.float64).reshape((3, 3))
31
+ c = np.empty((3, 3), dtype=np.float64)
32
+ blas._test_dgemm(1., a, b, 0., c)
33
+ assert_allclose(c, b)
34
+
35
+
36
+ class TestDGEMM:
37
+
38
+ def test_transposes(self):
39
+
40
+ a = np.arange(12, dtype=np.float64).reshape((3, 4))[:2,:2]
41
+ b = np.arange(1, 13, dtype=np.float64).reshape((4, 3))[:2,:2]
42
+ c = np.empty((2, 4), dtype=np.float64)[:2,:2]
43
+
44
+ blas._test_dgemm(1., a, b, 0., c)
45
+ assert_allclose(c, a.dot(b))
46
+
47
+ blas._test_dgemm(1., a.T, b, 0., c)
48
+ assert_allclose(c, a.T.dot(b))
49
+
50
+ blas._test_dgemm(1., a, b.T, 0., c)
51
+ assert_allclose(c, a.dot(b.T))
52
+
53
+ blas._test_dgemm(1., a.T, b.T, 0., c)
54
+ assert_allclose(c, a.T.dot(b.T))
55
+
56
+ blas._test_dgemm(1., a, b, 0., c.T)
57
+ assert_allclose(c, a.dot(b).T)
58
+
59
+ blas._test_dgemm(1., a.T, b, 0., c.T)
60
+ assert_allclose(c, a.T.dot(b).T)
61
+
62
+ blas._test_dgemm(1., a, b.T, 0., c.T)
63
+ assert_allclose(c, a.dot(b.T).T)
64
+
65
+ blas._test_dgemm(1., a.T, b.T, 0., c.T)
66
+ assert_allclose(c, a.T.dot(b.T).T)
67
+
68
+ def test_shapes(self):
69
+ a = np.arange(6, dtype=np.float64).reshape((3, 2))
70
+ b = np.arange(-6, 2, dtype=np.float64).reshape((2, 4))
71
+ c = np.empty((3, 4), dtype=np.float64)
72
+
73
+ blas._test_dgemm(1., a, b, 0., c)
74
+ assert_allclose(c, a.dot(b))
75
+
76
+ blas._test_dgemm(1., b.T, a.T, 0., c.T)
77
+ assert_allclose(c, b.T.dot(a.T).T)
78
+
79
+ class TestWfuncPointers:
80
+ """ Test the function pointers that are expected to fail on
81
+ Mac OS X without the additional entry statement in their definitions
82
+ in fblas_l1.pyf.src. """
83
+
84
+ def test_complex_args(self):
85
+
86
+ cx = np.array([.5 + 1.j, .25 - .375j, 12.5 - 4.j], np.complex64)
87
+ cy = np.array([.8 + 2.j, .875 - .625j, -1. + 2.j], np.complex64)
88
+
89
+ assert_allclose(blas._test_cdotc(cx, cy),
90
+ -17.6468753815+21.3718757629j)
91
+ assert_allclose(blas._test_cdotu(cx, cy),
92
+ -6.11562538147+30.3156242371j)
93
+
94
+ assert_equal(blas._test_icamax(cx), 3)
95
+
96
+ assert_allclose(blas._test_scasum(cx), 18.625)
97
+ assert_allclose(blas._test_scnrm2(cx), 13.1796483994)
98
+
99
+ assert_allclose(blas._test_cdotc(cx[::2], cy[::2]),
100
+ -18.1000003815+21.2000007629j)
101
+ assert_allclose(blas._test_cdotu(cx[::2], cy[::2]),
102
+ -6.10000038147+30.7999992371j)
103
+ assert_allclose(blas._test_scasum(cx[::2]), 18.)
104
+ assert_allclose(blas._test_scnrm2(cx[::2]), 13.1719398499)
105
+
106
+ def test_double_args(self):
107
+
108
+ x = np.array([5., -3, -.5], np.float64)
109
+ y = np.array([2, 1, .5], np.float64)
110
+
111
+ assert_allclose(blas._test_dasum(x), 8.5)
112
+ assert_allclose(blas._test_ddot(x, y), 6.75)
113
+ assert_allclose(blas._test_dnrm2(x), 5.85234975815)
114
+
115
+ assert_allclose(blas._test_dasum(x[::2]), 5.5)
116
+ assert_allclose(blas._test_ddot(x[::2], y[::2]), 9.75)
117
+ assert_allclose(blas._test_dnrm2(x[::2]), 5.0249376297)
118
+
119
+ assert_equal(blas._test_idamax(x), 1)
120
+
121
+ def test_float_args(self):
122
+
123
+ x = np.array([5., -3, -.5], np.float32)
124
+ y = np.array([2, 1, .5], np.float32)
125
+
126
+ assert_equal(blas._test_isamax(x), 1)
127
+
128
+ assert_allclose(blas._test_sasum(x), 8.5)
129
+ assert_allclose(blas._test_sdot(x, y), 6.75)
130
+ assert_allclose(blas._test_snrm2(x), 5.85234975815)
131
+
132
+ assert_allclose(blas._test_sasum(x[::2]), 5.5)
133
+ assert_allclose(blas._test_sdot(x[::2], y[::2]), 9.75)
134
+ assert_allclose(blas._test_snrm2(x[::2]), 5.0249376297)
135
+
136
+ def test_double_complex_args(self):
137
+
138
+ cx = np.array([.5 + 1.j, .25 - .375j, 13. - 4.j], np.complex128)
139
+ cy = np.array([.875 + 2.j, .875 - .625j, -1. + 2.j], np.complex128)
140
+
141
+ assert_equal(blas._test_izamax(cx), 3)
142
+
143
+ assert_allclose(blas._test_zdotc(cx, cy), -18.109375+22.296875j)
144
+ assert_allclose(blas._test_zdotu(cx, cy), -6.578125+31.390625j)
145
+
146
+ assert_allclose(blas._test_zdotc(cx[::2], cy[::2]), -18.5625+22.125j)
147
+ assert_allclose(blas._test_zdotu(cx[::2], cy[::2]), -6.5625+31.875j)
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cython_lapack.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numpy.testing import assert_allclose
2
+ from scipy.linalg import cython_lapack as cython_lapack
3
+ from scipy.linalg import lapack
4
+
5
+
6
+ class TestLamch:
7
+
8
+ def test_slamch(self):
9
+ lapack_slamch = lapack.get_lapack_funcs(
10
+ 'lamch', dtype='float32', ilp64='preferred'
11
+ )
12
+ for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']:
13
+ assert_allclose(cython_lapack._test_slamch(c),
14
+ lapack_slamch(c))
15
+
16
+ def test_dlamch(self):
17
+ lapack_dlamch = lapack.get_lapack_funcs(
18
+ 'lamch', dtype='float64', ilp64='preferred'
19
+ )
20
+
21
+ for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']:
22
+ assert_allclose(cython_lapack._test_dlamch(c),
23
+ lapack_dlamch(c))
24
+
25
+ def test_complex_ladiv(self):
26
+ cx = .5 + 1.j
27
+ cy = .875 + 2.j
28
+ assert_allclose(cython_lapack._test_zladiv(cy, cx), 1.95+0.1j)
29
+ assert_allclose(cython_lapack._test_cladiv(cy, cx), 1.95+0.1j)
30
+
31
+
32
+ class TestBlasInt:
33
+ """Test for blas_int/blas_bint types used in cython_blas/cython_lapack.
34
+
35
+ Note similar test is in test_blas.py: both cython_blas.pyx and cython_lapack.pyx
36
+ define the types, so we smoke test that `blas_int` and `blas_bint` types
37
+ can be cimported from both `cython_blas` and `cython_lapack` extensions.
38
+ """
39
+
40
+ def test_blas_int_size(self):
41
+ """Verify blas_int and blas_bint sizes matches the build configuration."""
42
+ from scipy.__config__ import CONFIG
43
+ size = cython_lapack._blas_int_size()
44
+ cython_blas_ilp64 = CONFIG['Build Dependencies']['blas']['cython blas ilp64']
45
+ if cython_blas_ilp64:
46
+ assert size == 8, f"ILP64 build but blas_int is {size} bytes"
47
+ else:
48
+ assert size == 4, f"LP64 build but blas_int is {size} bytes"
49
+
50
+ # also verify blas_bint size
51
+ # bint_sizes is a 2-tuple, (sizeof(blas_bint), sizeof(bint))
52
+ bint_sizes = cython_lapack._blas_bint_bint_sizes()
53
+ if cython_blas_ilp64:
54
+ assert bint_sizes == (8, 4)
55
+ else:
56
+ assert bint_sizes == (4, 4)
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.linalg import bandwidth, issymmetric, ishermitian
3
+ from scipy.conftest import skip_xp_invalid_arg
4
+ import pytest
5
+ from pytest import raises
6
+ from numpy.testing import assert_equal
7
+
8
+ BANDWIDTH_DTYPES = (
9
+ np.bool,
10
+ np.int8, np.int16, np.int32, np.int64,
11
+ np.uint8, np.uint16, np.uint32, np.uint64,
12
+ np.float32, np.float64,
13
+ np.complex64, np.complex128,
14
+ )
15
+
16
+
17
+ @skip_xp_invalid_arg
18
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
19
+ def test_bandwidth_dtypes():
20
+ n = 5
21
+ for dt in BANDWIDTH_DTYPES:
22
+ _ = bandwidth(np.zeros([n, n], dtype=dt))
23
+
24
+ unsupported_dtypes = [np.float16, np.longdouble, np.clongdouble,
25
+ np.bytes_, np.str_, np.void, np.object_,
26
+ np.datetime64, np.timedelta64]
27
+ for dt in unsupported_dtypes:
28
+ raises(TypeError, bandwidth, np.zeros([n, n], dtype=dt))
29
+
30
+
31
+ @pytest.mark.parametrize('T', BANDWIDTH_DTYPES)
32
+ def test_bandwidth_square_inputs(T):
33
+ n = 20
34
+ k = 4
35
+ R = np.zeros([n, n], dtype=T, order='F')
36
+ # form a banded matrix inplace
37
+ R[[x for x in range(n)], [x for x in range(n)]] = 1
38
+ R[[x for x in range(n-k)], [x for x in range(k, n)]] = 1
39
+ R[[x for x in range(1, n)], [x for x in range(n-1)]] = 1
40
+ R[[x for x in range(k, n)], [x for x in range(n-k)]] = 1
41
+ assert bandwidth(R) == (k, k)
42
+ A = np.array([
43
+ [1, 1, 0, 0, 0, 0, 0, 0],
44
+ [1, 0, 0, 0, 0, 0, 0, 0],
45
+ [0, 0, 0, 0, 0, 0, 0, 0],
46
+ [0, 0, 0, 0, 0, 0, 0, 0],
47
+ [0, 0, 0, 0, 0, 0, 0, 0],
48
+ [0, 0, 0, 0, 0, 1, 1, 1],
49
+ [0, 0, 0, 0, 0, 1, 0, 0],
50
+ [0, 0, 0, 0, 0, 1, 0, 0],
51
+ ])
52
+ assert bandwidth(A) == (2, 2)
53
+
54
+ A = np.array(
55
+ [
56
+ [[1, 0, 0], [0, 1, 0], [0, 0, 1]], # diagonal
57
+ [[0, 0, 1], [0, 0, 0], [0, 0, 0]], # upper triangular
58
+ [[0, 0, 0], [0, 0, 0], [1, 0, 0]], # lower triangular
59
+ [[0, 0, 1], [0, 0, 0], [1, 0, 0]], # full
60
+ [[0, 0, 1], [0, 0, 0], [0, 1, 0.]], # upper hessenberg
61
+ ]
62
+ )
63
+ lo, hi = bandwidth(A)
64
+ assert_equal(lo, [0, 0, 2, 2, 1])
65
+ assert_equal(hi, [0, 2, 0, 2, 2])
66
+
67
+
68
+ @skip_xp_invalid_arg
69
+ @pytest.mark.parametrize('T', BANDWIDTH_DTYPES)
70
+ def test_bandwidth_rect_inputs(T):
71
+ n, m = 10, 20
72
+ k = 5
73
+ R = np.zeros([n, m], dtype=T, order='F')
74
+ # form a banded matrix inplace
75
+ R[[x for x in range(n)], [x for x in range(n)]] = 1
76
+ R[[x for x in range(n-k)], [x for x in range(k, n)]] = 1
77
+ R[[x for x in range(1, n)], [x for x in range(n-1)]] = 1
78
+ R[[x for x in range(k, n)], [x for x in range(n-k)]] = 1
79
+ assert bandwidth(R) == (k, k)
80
+
81
+ R2 = np.tril(np.ones((2, 10, 2), dtype=T))
82
+ lo, hi = bandwidth(R2)
83
+ assert_equal(lo, [9, 9])
84
+ assert_equal(hi, [0, 0])
85
+
86
+ R3 = np.triu(np.ones((2, 10, 2), dtype=T))
87
+ lo, hi = bandwidth(R3)
88
+ assert_equal(lo, [0, 0])
89
+ assert_equal(hi, [1, 1])
90
+
91
+
92
+ @skip_xp_invalid_arg
93
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
94
+ def test_issymetric_ishermitian_dtypes():
95
+ n = 5
96
+ for t in np.typecodes['All']:
97
+ A = np.zeros([n, n], dtype=t)
98
+ if t in 'eUVOMm':
99
+ raises(TypeError, issymmetric, A)
100
+ raises(TypeError, ishermitian, A)
101
+ elif t == 'G': # No-op test. On win these pass on others fail.
102
+ pass
103
+ else:
104
+ assert issymmetric(A)
105
+ assert ishermitian(A)
106
+
107
+
108
+ def test_issymmetric_ishermitian_invalid_input():
109
+ A = np.array([1, 2, 3])
110
+ raises(ValueError, issymmetric, A)
111
+ raises(ValueError, ishermitian, A)
112
+ A = np.array([[[1, 2, 3], [4, 5, 6]]])
113
+ raises(ValueError, issymmetric, A)
114
+ raises(ValueError, ishermitian, A)
115
+ A = np.array([[1, 2, 3], [4, 5, 6]])
116
+ raises(ValueError, issymmetric, A)
117
+ raises(ValueError, ishermitian, A)
118
+
119
+
120
+ def test_issymetric_complex_decimals():
121
+ A = np.arange(1, 10).astype(complex).reshape(3, 3)
122
+ A += np.arange(-4, 5).astype(complex).reshape(3, 3)*1j
123
+ # make entries decimal
124
+ A /= np.pi
125
+ A = A + A.T
126
+ assert issymmetric(A)
127
+
128
+
129
+ def test_ishermitian_complex_decimals():
130
+ A = np.arange(1, 10).astype(complex).reshape(3, 3)
131
+ A += np.arange(-4, 5).astype(complex).reshape(3, 3)*1j
132
+ # make entries decimal
133
+ A /= np.pi
134
+ A = A + A.T.conj()
135
+ assert ishermitian(A)
136
+
137
+
138
+ def test_issymmetric_approximate_results():
139
+ n = 20
140
+ rng = np.random.RandomState(123456789)
141
+ x = rng.uniform(high=5., size=[n, n])
142
+ y = x @ x.T # symmetric
143
+ p = rng.standard_normal([n, n])
144
+ z = p @ y @ p.T
145
+ assert issymmetric(z, atol=1e-10)
146
+ assert issymmetric(z, atol=1e-10, rtol=0.)
147
+ assert issymmetric(z, atol=0., rtol=1e-12)
148
+ assert issymmetric(z, atol=1e-13, rtol=1e-12)
149
+
150
+
151
+ def test_ishermitian_approximate_results():
152
+ n = 20
153
+ rng = np.random.RandomState(987654321)
154
+ x = rng.uniform(high=5., size=[n, n])
155
+ y = x @ x.T # symmetric
156
+ p = rng.standard_normal([n, n]) + rng.standard_normal([n, n])*1j
157
+ z = p @ y @ p.conj().T
158
+ assert ishermitian(z, atol=1e-10)
159
+ assert ishermitian(z, atol=1e-10, rtol=0.)
160
+ assert ishermitian(z, atol=0., rtol=1e-12)
161
+ assert ishermitian(z, atol=1e-13, rtol=1e-12)
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_cholesky.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import numpy as np
3
+ from numpy.testing import assert_allclose
4
+ from pytest import raises as assert_raises
5
+
6
+ from numpy import array, transpose, zeros_like, empty
7
+ from scipy.linalg import (cholesky, cholesky_banded, cho_solve_banded,
8
+ cho_factor, cho_solve, LinAlgError)
9
+
10
+ from scipy.linalg._testutils import assert_no_overwrite
11
+ from .test_basic import parametrize_overwrite_arg
12
+
13
+
14
+ class TestCholesky:
15
+
16
+ def test_simple(self):
17
+ a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]]
18
+ c = cholesky(a)
19
+ assert_allclose(c.T @ c, a, atol=1e-14)
20
+ c = transpose(c)
21
+ a = c @ c.T
22
+ assert_allclose(cholesky(a, lower=1), c, atol=1e-14)
23
+
24
+ def test_check_finite(self):
25
+ a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]]
26
+ c = cholesky(a, check_finite=False)
27
+ assert_allclose(c.T @ c, a, atol=1e-14)
28
+ c = transpose(c)
29
+ a = c @ c.T
30
+ assert_allclose(cholesky(a, lower=1, check_finite=False), c, atol=1e-14)
31
+
32
+ def test_simple_complex(self):
33
+ m = array([[3+1j, 3+4j, 5], [0, 2+2j, 2+7j], [0, 0, 7+4j]])
34
+ a = np.conj(m.T) @ m
35
+ c = cholesky(a)
36
+ a1 = np.conj(c.T) @ c
37
+ assert_allclose(a, a1)
38
+ c = transpose(c)
39
+ a = c @ np.conj(c.T)
40
+ assert_allclose(cholesky(a, lower=1), c, atol=1e-14)
41
+
42
+ @pytest.mark.parametrize("n", [5, 10, 20])
43
+ @pytest.mark.parametrize("dtype", [np.float32, np.float64,
44
+ np.complex64, np.complex128])
45
+ @pytest.mark.parametrize("order", ["F", "C"])
46
+ def test_random(self, n, dtype, order):
47
+ atol = 5e-4 if dtype in [np.float32, np.complex64] else 1e-12
48
+ rng = np.random.default_rng(seed=12345)
49
+
50
+ for k in range(2):
51
+ m = rng.normal(size=(n, n)).astype(dtype)
52
+ if np.issubdtype(dtype, np.complexfloating):
53
+ m += 1j * rng.normal(size=(n, n)).astype(dtype)
54
+ for i in range(n):
55
+ m[i, i] = 20*(.1+m[i, i])
56
+
57
+ a = np.asarray(np.conj(m.T) @ m, order=order)
58
+
59
+ c = cholesky(a, lower=0)
60
+ a1 = np.conj(c.T) @ c
61
+ assert_allclose(a, a1, atol=atol)
62
+
63
+ c = transpose(c)
64
+ a = c @ np.conj(c.T)
65
+ assert_allclose(cholesky(a, lower=1), c, atol=atol)
66
+
67
+ @pytest.mark.xslow
68
+ def test_int_overflow(self):
69
+ # regression test for
70
+ # https://github.com/scipy/scipy/issues/17436
71
+ # the problem was an int overflow in zeroing out
72
+ # the unused triangular part
73
+ n = 47_000
74
+ x = np.eye(n, dtype=np.float64, order='F')
75
+ x[:4, :4] = np.array([[4, -2, 3, -1],
76
+ [-2, 4, -3, 1],
77
+ [3, -3, 5, 0],
78
+ [-1, 1, 0, 5]])
79
+
80
+ cholesky(x, check_finite=False, overwrite_a=True) # should not segfault
81
+
82
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
83
+ @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
84
+ def test_empty(self, dt, dt_b):
85
+ a = empty((0, 0), dtype=dt)
86
+
87
+ c = cholesky(a)
88
+ assert c.shape == (0, 0)
89
+ assert c.dtype == cholesky(np.eye(2, dtype=dt)).dtype
90
+
91
+ c_and_lower = (c, True)
92
+ b = np.asarray([], dtype=dt_b)
93
+ x = cho_solve(c_and_lower, b)
94
+ assert x.shape == (0,)
95
+ assert x.dtype == cho_solve((np.eye(2, dtype=dt), True),
96
+ np.ones(2, dtype=dt_b)).dtype
97
+
98
+ b = empty((0, 0), dtype=dt_b)
99
+ x = cho_solve(c_and_lower, b)
100
+ assert x.shape == (0, 0)
101
+ assert x.dtype == cho_solve((np.eye(2, dtype=dt), True),
102
+ np.ones(2, dtype=dt_b)).dtype
103
+
104
+ a1 = array([])
105
+ a2 = array([[]])
106
+ a3 = []
107
+ a4 = [[]]
108
+ for x in ([a1, a2, a3, a4]):
109
+ assert_raises(ValueError, cholesky, x)
110
+
111
+ @pytest.mark.parametrize("shape", [(3,), (2, 3), (3, 2)])
112
+ def test_invalid_shape(self, shape):
113
+ rng = np.random.default_rng(seed=12345)
114
+ a = rng.normal(size=shape)
115
+
116
+ with pytest.raises(ValueError, match="Expected a square matrix"):
117
+ cholesky(a)
118
+
119
+ @pytest.mark.parametrize("dtype", [np.float32, np.float64,
120
+ np.complex64, np.complex128])
121
+ @pytest.mark.parametrize("order", ["C", "F"])
122
+ def test_non_posdef(self, dtype, order):
123
+ n = 10
124
+ rng = np.random.default_rng(seed=12345)
125
+
126
+ lmbd = np.diag(-np.abs(rng.normal(size=(n,))).astype(dtype))
127
+ x = rng.normal(size=(n, n)).astype(dtype)
128
+ if np.issubdtype(dtype, np.complexfloating):
129
+ x += 1j * rng.normal(size=(n, n)).astype(dtype)
130
+
131
+ a = np.asarray(x @ lmbd @ np.conj(x.T), order=order)
132
+
133
+ with pytest.raises(LinAlgError, match="Internal potrf return info"):
134
+ cholesky(a)
135
+
136
+ @parametrize_overwrite_arg
137
+ @pytest.mark.parametrize("dtype", [int, float])
138
+ @pytest.mark.parametrize("order", ["C", "F"])
139
+ def test_overwrite_args(self, overwrite_kw, dtype, order):
140
+ rng = np.random.default_rng(seed=12345)
141
+ n = 5
142
+
143
+ x = rng.normal(size=(n, n))
144
+ x = x.astype(dtype)
145
+ a = x @ x.T
146
+ a = a.astype(dtype, order=order)
147
+ a_ref = np.copy(a)
148
+
149
+ c = cholesky(a, **overwrite_kw)
150
+ overwrite_a = overwrite_kw.get("overwrite_a", False)
151
+ a_inplace = (overwrite_a and (dtype is not int)
152
+ and (a.flags["F_CONTIGUOUS"] or a.flags["C_CONTIGUOUS"]))
153
+
154
+ assert np.shares_memory(a, c) == a_inplace
155
+ assert np.all(a == a_ref) != a_inplace
156
+
157
+ @pytest.mark.parametrize("lower", [True, False])
158
+ def test_overwrite_cleaning(self, lower):
159
+ # Since only half the array is copied over, this checks if the other
160
+ # half is correctly put to 0 when the input array is passed in instead.
161
+ rng = np.random.default_rng(seed=12345)
162
+ n = 5
163
+
164
+ x = rng.normal(size=(n, n))
165
+ a = np.asfortranarray(x @ x.T)
166
+ a_ref = np.copy(a)
167
+
168
+ c = cholesky(a, lower=lower, overwrite_a=True)
169
+
170
+ if lower:
171
+ assert_allclose(np.triu(a, k=1), np.zeros_like(a), atol=1e-14)
172
+ assert_allclose(c @ c.T, a_ref, atol=1e-14)
173
+ else:
174
+ assert_allclose(np.tril(a, k=-1), np.zeros_like(a), atol=1e-14)
175
+ assert_allclose(c.T @ c, a_ref, atol=1e-14)
176
+
177
+ @pytest.mark.parametrize("lower", [True, False])
178
+ @pytest.mark.parametrize("order", ['C', 'F', 'noncontig_C', 'noncontig_F'])
179
+ @pytest.mark.parametrize("overwrite_a", [True, False])
180
+ @pytest.mark.parametrize("dtype", [np.float64, np.complex128])
181
+ def test_nan_in_unused_triangle(self, lower, order, overwrite_a, dtype):
182
+ # The unused triangle should never be read, so NaN there must not
183
+ # affect the result.
184
+ rng = np.random.default_rng(seed=12345)
185
+ n = 5
186
+ x = rng.normal(size=(n, n))
187
+ if np.issubdtype(dtype, np.complexfloating):
188
+ x = x + 1j * rng.normal(size=(n, n))
189
+ a = (x @ x.conj().T + n * np.eye(n)).astype(dtype)
190
+ c_ref = cholesky(a, lower=lower)
191
+
192
+ # Prepare the array in the desired layout
193
+ if order.startswith('noncontig'):
194
+ # Unequal strides to probe strided path thoroughly
195
+ big_order = 'F' if order.endswith('_F') else 'C'
196
+ a_big = np.zeros((2*n, 3*n), dtype=dtype, order=big_order)
197
+ a_big[::2, ::3] = a
198
+ a_nan = a_big[::2, ::3] # non-contiguous view
199
+ assert not a_nan.flags['C_CONTIGUOUS']
200
+ assert not a_nan.flags['F_CONTIGUOUS']
201
+ else:
202
+ a_nan = np.array(a, order=order)
203
+
204
+ # Put NaN in the unused triangle
205
+ if lower:
206
+ a_nan[np.triu_indices(n, 1)] = np.nan
207
+ else:
208
+ a_nan[np.tril_indices(n, -1)] = np.nan
209
+
210
+ c = cholesky(a_nan, lower=lower, overwrite_a=overwrite_a,
211
+ check_finite=False)
212
+ assert_allclose(c, c_ref, atol=1e-14)
213
+ # Verify reconstruction
214
+ if lower:
215
+ assert_allclose(c @ c.conj().T, a, atol=1e-13)
216
+ else:
217
+ assert_allclose(c.conj().T @ c, a, atol=1e-13)
218
+
219
+
220
+ class TestCholeskyBanded:
221
+ """Tests for cholesky_banded() and cho_solve_banded."""
222
+
223
+ def test_check_finite(self):
224
+ # Symmetric positive definite banded matrix `a`
225
+ a = array([[4.0, 1.0, 0.0, 0.0],
226
+ [1.0, 4.0, 0.5, 0.0],
227
+ [0.0, 0.5, 4.0, 0.2],
228
+ [0.0, 0.0, 0.2, 4.0]])
229
+ # Banded storage form of `a`.
230
+ ab = array([[-1.0, 1.0, 0.5, 0.2],
231
+ [4.0, 4.0, 4.0, 4.0]])
232
+ c = cholesky_banded(ab, lower=False, check_finite=False)
233
+ ufac = zeros_like(a)
234
+ ufac[list(range(4)), list(range(4))] = c[-1]
235
+ ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:]
236
+ assert_allclose(a, ufac.T @ ufac, atol=1e-14)
237
+
238
+ b = array([0.0, 0.5, 4.2, 4.2])
239
+ x = cho_solve_banded((c, False), b, check_finite=False)
240
+ assert_allclose(x, [0.0, 0.0, 1.0, 1.0], atol=1e-14)
241
+
242
+ def test_upper_real(self):
243
+ # Symmetric positive definite banded matrix `a`
244
+ a = array([[4.0, 1.0, 0.0, 0.0],
245
+ [1.0, 4.0, 0.5, 0.0],
246
+ [0.0, 0.5, 4.0, 0.2],
247
+ [0.0, 0.0, 0.2, 4.0]])
248
+ # Banded storage form of `a`.
249
+ ab = array([[-1.0, 1.0, 0.5, 0.2],
250
+ [4.0, 4.0, 4.0, 4.0]])
251
+ c = cholesky_banded(ab, lower=False)
252
+ ufac = zeros_like(a)
253
+ ufac[list(range(4)), list(range(4))] = c[-1]
254
+ ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:]
255
+ assert_allclose(a, ufac.T @ ufac, atol=1e-14)
256
+
257
+ b = array([0.0, 0.5, 4.2, 4.2])
258
+ x = cho_solve_banded((c, False), b)
259
+ assert_allclose(x, [0.0, 0.0, 1.0, 1.0], atol=1e-14)
260
+
261
+ def test_upper_complex(self):
262
+ # Hermitian positive definite banded matrix `a`
263
+ a = array([[4.0, 1.0, 0.0, 0.0],
264
+ [1.0, 4.0, 0.5, 0.0],
265
+ [0.0, 0.5, 4.0, -0.2j],
266
+ [0.0, 0.0, 0.2j, 4.0]])
267
+ # Banded storage form of `a`.
268
+ ab = array([[-1.0, 1.0, 0.5, -0.2j],
269
+ [4.0, 4.0, 4.0, 4.0]])
270
+ c = cholesky_banded(ab, lower=False)
271
+ ufac = zeros_like(a)
272
+ ufac[list(range(4)), list(range(4))] = c[-1]
273
+ ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:]
274
+ assert_allclose(a, np.conj(ufac.T) @ ufac, atol=1e-14)
275
+
276
+ b = array([0.0, 0.5, 4.0-0.2j, 0.2j + 4.0])
277
+ x = cho_solve_banded((c, False), b)
278
+ assert_allclose(x, [0.0, 0.0, 1.0, 1.0], atol=1e-14)
279
+
280
+ def test_lower_real(self):
281
+ # Symmetric positive definite banded matrix `a`
282
+ a = array([[4.0, 1.0, 0.0, 0.0],
283
+ [1.0, 4.0, 0.5, 0.0],
284
+ [0.0, 0.5, 4.0, 0.2],
285
+ [0.0, 0.0, 0.2, 4.0]])
286
+ # Banded storage form of `a`.
287
+ ab = array([[4.0, 4.0, 4.0, 4.0],
288
+ [1.0, 0.5, 0.2, -1.0]])
289
+ c = cholesky_banded(ab, lower=True)
290
+ lfac = zeros_like(a)
291
+ lfac[list(range(4)), list(range(4))] = c[0]
292
+ lfac[(1, 2, 3), (0, 1, 2)] = c[1, :3]
293
+ assert_allclose(a, lfac @ lfac.T, atol=1e-14)
294
+
295
+ b = array([0.0, 0.5, 4.2, 4.2])
296
+ x = cho_solve_banded((c, True), b)
297
+ assert_allclose(x, [0.0, 0.0, 1.0, 1.0], atol=1e-14)
298
+
299
+ def test_lower_complex(self):
300
+ # Hermitian positive definite banded matrix `a`
301
+ a = array([[4.0, 1.0, 0.0, 0.0],
302
+ [1.0, 4.0, 0.5, 0.0],
303
+ [0.0, 0.5, 4.0, -0.2j],
304
+ [0.0, 0.0, 0.2j, 4.0]])
305
+ # Banded storage form of `a`.
306
+ ab = array([[4.0, 4.0, 4.0, 4.0],
307
+ [1.0, 0.5, 0.2j, -1.0]])
308
+ c = cholesky_banded(ab, lower=True)
309
+ lfac = zeros_like(a)
310
+ lfac[list(range(4)), list(range(4))] = c[0]
311
+ lfac[(1, 2, 3), (0, 1, 2)] = c[1, :3]
312
+ assert_allclose(a, lfac @ np.conj(lfac.T), atol=1e-14)
313
+
314
+ b = array([0.0, 0.5j, 3.8j, 3.8])
315
+ x = cho_solve_banded((c, True), b)
316
+ assert_allclose(x, [0.0, 0.0, 1.0j, 1.0], atol=1e-14)
317
+
318
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
319
+ @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
320
+ def test_empty(self, dt, dt_b):
321
+ ab = empty((0, 0), dtype=dt)
322
+
323
+ cb = cholesky_banded(ab)
324
+ assert cb.shape == (0, 0)
325
+
326
+ m = cholesky_banded(np.array([[0, 0], [1, 1]], dtype=dt))
327
+ assert cb.dtype == m.dtype
328
+
329
+ cb_and_lower = (cb, True)
330
+ b = np.asarray([], dtype=dt_b)
331
+ x = cho_solve_banded(cb_and_lower, b)
332
+ assert x.shape == (0,)
333
+
334
+ dtype_nonempty = cho_solve_banded((m, True), np.ones(2, dtype=dt_b)).dtype
335
+ assert x.dtype == dtype_nonempty
336
+
337
+ b = empty((0, 0), dtype=dt_b)
338
+ x = cho_solve_banded(cb_and_lower, b)
339
+ assert x.shape == (0, 0)
340
+ assert x.dtype == dtype_nonempty
341
+
342
+
343
+ class TestOverwrite:
344
+ def test_cholesky(self):
345
+ assert_no_overwrite(cholesky, [(3, 3)])
346
+
347
+ def test_cho_factor(self):
348
+ assert_no_overwrite(cho_factor, [(3, 3)])
349
+
350
+ def test_cho_solve(self):
351
+ x = array([[2, -1, 0], [-1, 2, -1], [0, -1, 2]])
352
+ xcho = cho_factor(x)
353
+ assert_no_overwrite(lambda b: cho_solve(xcho, b), [(3,)])
354
+
355
+ def test_cholesky_banded(self):
356
+ assert_no_overwrite(cholesky_banded, [(2, 3)])
357
+
358
+ def test_cho_solve_banded(self):
359
+ x = array([[0, -1, -1], [2, 2, 2]])
360
+ xcho = cholesky_banded(x)
361
+ assert_no_overwrite(lambda b: cho_solve_banded((xcho, False), b),
362
+ [(3,)])
363
+
364
+
365
+ class TestChoFactor:
366
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
367
+ def test_empty(self, dt):
368
+ a = np.empty((0, 0), dtype=dt)
369
+ x, lower = cho_factor(a)
370
+
371
+ assert x.shape == (0, 0)
372
+
373
+ xx, lower = cho_factor(np.eye(2, dtype=dt))
374
+ assert x.dtype == xx.dtype
375
+
376
+ @pytest.mark.parametrize("n", [5, 10, 20])
377
+ @pytest.mark.parametrize("dtype", [np.float32, np.float64,
378
+ np.complex64, np.complex128])
379
+ @pytest.mark.parametrize("order", ["C", "F"])
380
+ @pytest.mark.parametrize("lower", [True, False])
381
+ def test_random(self, n, dtype, order, lower):
382
+ atol = 1e-5 if dtype in [np.float32, np.complex64] else 1e-12
383
+ rng = np.random.default_rng(seed=12345)
384
+
385
+ lmbd = np.diag(np.abs(rng.normal(size=(n,)).astype(dtype)))
386
+ x = rng.normal(size=(n, n)).astype(dtype)
387
+ if np.issubdtype(dtype, np.complexfloating):
388
+ x += 1j * rng.normal(size=(n, n)).astype(dtype)
389
+
390
+ a = np.asarray(x @ lmbd @ np.conj(x.T), order=order)
391
+ c = cholesky(a, lower=lower)
392
+ c_f, lower_out = cho_factor(a, lower=lower)
393
+
394
+ assert lower_out == lower
395
+
396
+ # Theoretically exactly equal
397
+ # For `cho_factor` the other half of the matrix is irrelevant.
398
+ if lower:
399
+ l = np.tril(c_f)
400
+ assert_allclose(c, l, atol=atol)
401
+ assert_allclose(a, l @ np.conj(l.T), atol=atol)
402
+ else:
403
+ u = np.triu(c_f)
404
+ assert_allclose(c, u, atol=atol)
405
+ assert_allclose(a, np.conj(u.T) @ u, atol=atol)
406
+
407
+ @pytest.mark.parametrize("shape", [(3,), (3, 2), (2, 3)])
408
+ def test_invalid_shape(self, shape):
409
+ rng = np.random.default_rng(seed=12345)
410
+ a = rng.normal(size=shape)
411
+
412
+ with pytest.raises(ValueError, match="Expected a square matrix or batch"):
413
+ cho_factor(a)
414
+
415
+ @pytest.mark.parametrize("dtype", [np.float32, np.float64,
416
+ np.complex64, np.complex128])
417
+ @pytest.mark.parametrize("order", ["C", "F"])
418
+ def test_non_posdef(self, dtype, order):
419
+ n = 10
420
+ rng = np.random.default_rng(seed=12345)
421
+
422
+ lmbd = np.diag(-np.abs(rng.normal(size=(n,))).astype(dtype))
423
+ x = rng.normal(size=(n, n)).astype(dtype)
424
+ if np.issubdtype(dtype, np.complexfloating):
425
+ x += 1j * rng.normal(size=(n, n)).astype(dtype)
426
+
427
+ a = np.asarray(x @ lmbd @ np.conj(x.T), order=order)
428
+
429
+ with pytest.raises(LinAlgError, match="Internal potrf return info"):
430
+ cho_factor(a)
431
+
432
+ @parametrize_overwrite_arg
433
+ @pytest.mark.parametrize("dtype", [int, float])
434
+ @pytest.mark.parametrize("order", ["C", "F"])
435
+ @pytest.mark.parametrize("lower", [True, False])
436
+ def test_overwrite_args(self, overwrite_kw, dtype, order, lower):
437
+ rng = np.random.default_rng(seed=12345)
438
+ n = 5
439
+
440
+ x = rng.normal(size=(n, n))
441
+ x = x.astype(dtype)
442
+ a = x @ x.T
443
+ a = a.astype(dtype, order=order)
444
+ a_ref = np.copy(a)
445
+
446
+ c, lower = cho_factor(a, **overwrite_kw, lower=lower)
447
+ overwrite_a = overwrite_kw.get("overwrite_a", False)
448
+ a_inplace = (overwrite_a and (dtype is not int)
449
+ and (a.flags["F_CONTIGUOUS"] or a.flags["C_CONTIGUOUS"]))
450
+
451
+ assert np.shares_memory(a, c) == a_inplace
452
+ assert np.all(a == a_ref) != a_inplace
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_cossin.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import numpy as np
3
+ from numpy.random import default_rng
4
+ from numpy.testing import assert_allclose
5
+
6
+ from scipy import linalg
7
+ from scipy.linalg.lapack import _compute_lwork
8
+ from scipy.stats import ortho_group, unitary_group
9
+ from scipy.linalg import cossin, get_lapack_funcs
10
+
11
+ REAL_DTYPES = (np.float32, np.float64)
12
+ COMPLEX_DTYPES = (np.complex64, np.complex128)
13
+ DTYPES = REAL_DTYPES + COMPLEX_DTYPES
14
+
15
+
16
+ @pytest.mark.parametrize('dtype_', DTYPES)
17
+ @pytest.mark.parametrize('m, p, q',
18
+ [
19
+ (2, 1, 1),
20
+ (3, 2, 1),
21
+ (3, 1, 2),
22
+ (4, 2, 2),
23
+ (4, 1, 2),
24
+ (40, 12, 20),
25
+ (40, 30, 1),
26
+ (40, 1, 30),
27
+ (100, 50, 1),
28
+ (100, 50, 50),
29
+ ])
30
+ @pytest.mark.parametrize('swap_sign', [True, False])
31
+ def test_cossin(dtype_, m, p, q, swap_sign):
32
+ rng = default_rng(1708093570726217)
33
+ if dtype_ in COMPLEX_DTYPES:
34
+ x = np.array(unitary_group.rvs(m, random_state=rng), dtype=dtype_)
35
+ else:
36
+ x = np.array(ortho_group.rvs(m, random_state=rng), dtype=dtype_)
37
+
38
+ u, cs, vh = cossin(x, p, q,
39
+ swap_sign=swap_sign)
40
+ assert_allclose(x, u @ cs @ vh, rtol=0., atol=m*1e3*np.finfo(dtype_).eps)
41
+ assert u.dtype == dtype_
42
+ # Test for float32 or float 64
43
+ assert cs.dtype == np.real(u).dtype
44
+ assert vh.dtype == dtype_
45
+
46
+ u, cs, vh = cossin([x[:p, :q], x[:p, q:], x[p:, :q], x[p:, q:]],
47
+ swap_sign=swap_sign)
48
+ assert_allclose(x, u @ cs @ vh, rtol=0., atol=m*1e3*np.finfo(dtype_).eps)
49
+ assert u.dtype == dtype_
50
+ assert cs.dtype == np.real(u).dtype
51
+ assert vh.dtype == dtype_
52
+
53
+ _, cs2, vh2 = cossin(x, p, q,
54
+ compute_u=False,
55
+ swap_sign=swap_sign)
56
+ assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps)
57
+ assert_allclose(vh, vh2, rtol=0., atol=10*np.finfo(dtype_).eps)
58
+
59
+ u2, cs2, _ = cossin(x, p, q,
60
+ compute_vh=False,
61
+ swap_sign=swap_sign)
62
+ assert_allclose(u, u2, rtol=0., atol=10*np.finfo(dtype_).eps)
63
+ assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps)
64
+
65
+ _, cs2, _ = cossin(x, p, q,
66
+ compute_u=False,
67
+ compute_vh=False,
68
+ swap_sign=swap_sign)
69
+ assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps)
70
+
71
+
72
+ def test_cossin_mixed_types():
73
+ rng = default_rng(1708093736390459)
74
+ x = np.array(ortho_group.rvs(4, random_state=rng), dtype=np.float64)
75
+ u, cs, vh = cossin([x[:2, :2],
76
+ np.array(x[:2, 2:], dtype=np.complex128),
77
+ x[2:, :2],
78
+ x[2:, 2:]])
79
+
80
+ assert u.dtype == np.complex128
81
+ assert cs.dtype == np.float64
82
+ assert vh.dtype == np.complex128
83
+ assert_allclose(x, u @ cs @ vh, rtol=0.,
84
+ atol=1e4 * np.finfo(np.complex128).eps)
85
+
86
+
87
+ def test_cossin_error_incorrect_subblocks():
88
+ with pytest.raises(ValueError, match="be due to missing p, q arguments."):
89
+ cossin(([1, 2], [3, 4, 5], [6, 7], [8, 9, 10]))
90
+
91
+
92
+ def test_cossin_error_empty_subblocks():
93
+ with pytest.raises(ValueError, match="x11.*empty"):
94
+ cossin(([], [], [], []))
95
+ with pytest.raises(ValueError, match="x12.*empty"):
96
+ cossin(([1, 2], [], [6, 7], [8, 9, 10]))
97
+ with pytest.raises(ValueError, match="x21.*empty"):
98
+ cossin(([1, 2], [3, 4, 5], [], [8, 9, 10]))
99
+ with pytest.raises(ValueError, match="x22.*empty"):
100
+ cossin(([1, 2], [3, 4, 5], [2], []))
101
+
102
+
103
+ def test_cossin_error_missing_partitioning():
104
+ with pytest.raises(ValueError, match=".*exactly four arrays.* got 2"):
105
+ cossin(unitary_group.rvs(2))
106
+
107
+ with pytest.raises(ValueError, match=".*might be due to missing p, q"):
108
+ cossin(unitary_group.rvs(4))
109
+
110
+
111
+ def test_cossin_error_non_iterable():
112
+ with pytest.raises(ValueError, match="containing the subblocks of X"):
113
+ cossin(12j)
114
+
115
+ def test_cossin_error_invalid_shape():
116
+ # Invalid x12 dimensions
117
+ p, q = 3, 4
118
+ invalid_x12 = np.ones((p, q + 2))
119
+ valid_ones = np.ones((p, q))
120
+ with pytest.raises(ValueError,
121
+ match=r"Invalid x12 dimensions: desired \(3, 4\), got \(3, 6\)"):
122
+ cossin((valid_ones, invalid_x12, valid_ones, valid_ones))
123
+
124
+ # Invalid x21 dimensions
125
+ invalid_x21 = np.ones(p + 2)
126
+ with pytest.raises(ValueError,
127
+ match=r"Invalid x21 dimensions: desired \(3, 4\), got \(1, 5\)"):
128
+ cossin((valid_ones, valid_ones, invalid_x21, valid_ones))
129
+
130
+ def test_cossin_error_non_square():
131
+ with pytest.raises(ValueError, match="only supports square"):
132
+ cossin(np.array([[1, 2]]), 1, 1)
133
+
134
+
135
+ def test_cossin_error_partitioning():
136
+ x = np.array(ortho_group.rvs(4), dtype=np.float64)
137
+ with pytest.raises(ValueError, match="invalid p=0.*0<p<4.*"):
138
+ cossin(x, 0, 1)
139
+ with pytest.raises(ValueError, match="invalid p=4.*0<p<4.*"):
140
+ cossin(x, 4, 1)
141
+ with pytest.raises(ValueError, match="invalid q=-2.*0<q<4.*"):
142
+ cossin(x, 1, -2)
143
+ with pytest.raises(ValueError, match="invalid q=5.*0<q<4.*"):
144
+ cossin(x, 1, 5)
145
+
146
+
147
+ @pytest.mark.parametrize("dtype_", DTYPES)
148
+ def test_cossin_separate(dtype_):
149
+ rng = default_rng(1708093590167096)
150
+ m, p, q = 98, 37, 61
151
+
152
+ pfx = 'or' if dtype_ in REAL_DTYPES else 'un'
153
+ X = (ortho_group.rvs(m, random_state=rng) if pfx == 'or'
154
+ else unitary_group.rvs(m, random_state=rng))
155
+ X = np.array(X, dtype=dtype_)
156
+
157
+ drv, dlw = get_lapack_funcs((pfx + 'csd', pfx + 'csd_lwork'), [X])
158
+ lwval = _compute_lwork(dlw, m, p, q)
159
+ lwvals = {'lwork': lwval} if pfx == 'or' else dict(zip(['lwork',
160
+ 'lrwork'],
161
+ lwval))
162
+
163
+ *_, theta, u1, u2, v1t, v2t, _ = \
164
+ drv(X[:p, :q], X[:p, q:], X[p:, :q], X[p:, q:], **lwvals)
165
+
166
+ (u1_2, u2_2), theta2, (v1t_2, v2t_2) = cossin(X, p, q, separate=True)
167
+
168
+ assert_allclose(u1_2, u1, rtol=0., atol=10*np.finfo(dtype_).eps)
169
+ assert_allclose(u2_2, u2, rtol=0., atol=10*np.finfo(dtype_).eps)
170
+ assert_allclose(v1t_2, v1t, rtol=0., atol=10*np.finfo(dtype_).eps)
171
+ assert_allclose(v2t_2, v2t, rtol=0., atol=10*np.finfo(dtype_).eps)
172
+ assert_allclose(theta2, theta, rtol=0., atol=10*np.finfo(dtype_).eps)
173
+
174
+
175
+ @pytest.mark.parametrize("m", [2, 5, 10, 15, 20])
176
+ @pytest.mark.parametrize("p", [1, 4, 9, 14, 19])
177
+ @pytest.mark.parametrize("q", [1, 4, 9, 14, 19])
178
+ @pytest.mark.parametrize("swap_sign", [True, False])
179
+ def test_properties(m, p, q, swap_sign):
180
+ # Test all the properties advertised in `linalg.cossin` documentation.
181
+ # There may be some overlap with tests above, but this is sensitive to
182
+ # the bug reported in gh-19365 and more.
183
+ if (p >= m) or (q >= m):
184
+ pytest.skip("`0 < p < m` and `0 < q < m` must hold")
185
+
186
+ # Generate unitary input
187
+ rng = np.random.default_rng(329548272348596421)
188
+ X = unitary_group.rvs(m, random_state=rng)
189
+ np.testing.assert_allclose(X @ X.conj().T, np.eye(m), atol=1e-15)
190
+
191
+ # Perform the decomposition
192
+ u0, cs0, vh0 = linalg.cossin(X, p=p, q=q, separate=True, swap_sign=swap_sign)
193
+ u1, u2 = u0
194
+ v1, v2 = vh0
195
+ v1, v2 = v1.conj().T, v2.conj().T
196
+
197
+ # "U1, U2, V1, V2 are square orthogonal/unitary matrices
198
+ # of dimensions (p,p), (m-p,m-p), (q,q), and (m-q,m-q) respectively"
199
+ np.testing.assert_allclose(u1 @ u1.conj().T, np.eye(p), atol=1e-13)
200
+ np.testing.assert_allclose(u2 @ u2.conj().T, np.eye(m-p), atol=1e-13)
201
+ np.testing.assert_allclose(v1 @ v1.conj().T, np.eye(q), atol=1e-13)
202
+ np.testing.assert_allclose(v2 @ v2.conj().T, np.eye(m-q), atol=1e-13)
203
+
204
+ # "and C and S are (r, r) nonnegative diagonal matrices..."
205
+ C = np.diag(np.cos(cs0))
206
+ S = np.diag(np.sin(cs0))
207
+ # "...satisfying C^2 + S^2 = I where r = min(p, m-p, q, m-q)."
208
+ r = min(p, m-p, q, m-q)
209
+ np.testing.assert_allclose(C**2 + S**2, np.eye(r))
210
+
211
+ # "Moreover, the rank of the identity matrices are
212
+ # min(p, q) - r, min(p, m - q) - r, min(m - p, q) - r,
213
+ # and min(m - p, m - q) - r respectively."
214
+ I11 = np.eye(min(p, q) - r)
215
+ I12 = np.eye(min(p, m - q) - r)
216
+ I21 = np.eye(min(m - p, q) - r)
217
+ I22 = np.eye(min(m - p, m - q) - r)
218
+
219
+ # From:
220
+ # ┌ ┐
221
+ # │ I 0 0 │ 0 0 0 │
222
+ # ┌ ┐ ┌ ┐│ 0 C 0 │ 0 -S 0 │┌ ┐*
223
+ # │ X11 │ X12 │ │ U1 │ ││ 0 0 0 │ 0 0 -I ││ V1 │ │
224
+ # │ ────┼──── │ = │────┼────││─────────┼─────────││────┼────│
225
+ # │ X21 │ X22 │ │ │ U2 ││ 0 0 0 │ I 0 0 ││ │ V2 │
226
+ # └ ┘ └ ┘│ 0 S 0 │ 0 C 0 │└ ┘
227
+ # │ 0 0 I │ 0 0 0 │
228
+ # └ ┘
229
+
230
+ # We can see that U and V are block diagonal matrices like so:
231
+ U = linalg.block_diag(u1, u2)
232
+ V = linalg.block_diag(v1, v2)
233
+
234
+ # And the center matrix, which we'll call Q here, must be:
235
+ Q11 = np.zeros((u1.shape[1], v1.shape[0]))
236
+ IC11 = linalg.block_diag(I11, C)
237
+ Q11[:IC11.shape[0], :IC11.shape[1]] = IC11
238
+
239
+ Q12 = np.zeros((u1.shape[1], v2.shape[0]))
240
+ SI12 = linalg.block_diag(S, I12) if swap_sign else linalg.block_diag(-S, -I12)
241
+ Q12[-SI12.shape[0]:, -SI12.shape[1]:] = SI12
242
+
243
+ Q21 = np.zeros((u2.shape[1], v1.shape[0]))
244
+ SI21 = linalg.block_diag(-S, -I21) if swap_sign else linalg.block_diag(S, I21)
245
+ Q21[-SI21.shape[0]:, -SI21.shape[1]:] = SI21
246
+
247
+ Q22 = np.zeros((u2.shape[1], v2.shape[0]))
248
+ IC22 = linalg.block_diag(I22, C)
249
+ Q22[:IC22.shape[0], :IC22.shape[1]] = IC22
250
+
251
+ Q = np.block([[Q11, Q12], [Q21, Q22]])
252
+
253
+ # Confirm that `cossin` decomposes `X` as shown
254
+ np.testing.assert_allclose(X, U @ Q @ V.conj().T)
255
+
256
+ # And check that `separate=False` agrees
257
+ U0, CS0, Vh0 = linalg.cossin(X, p=p, q=q, swap_sign=swap_sign)
258
+ np.testing.assert_allclose(U, U0)
259
+ np.testing.assert_allclose(Q, CS0)
260
+ np.testing.assert_allclose(V, Vh0.conj().T)
261
+
262
+ # Confirm that `compute_u`/`compute_vh` don't affect the results
263
+ kwargs = dict(p=p, q=q, swap_sign=swap_sign)
264
+
265
+ # `compute_u=False`
266
+ u, cs, vh = linalg.cossin(X, separate=True, compute_u=False, **kwargs)
267
+ assert u[0].shape == (0, 0) # probably not ideal, but this is what it does
268
+ assert u[1].shape == (0, 0)
269
+ assert_allclose(cs, cs0, rtol=1e-15)
270
+ assert_allclose(vh[0], vh0[0], rtol=1e-15)
271
+ assert_allclose(vh[1], vh0[1], rtol=1e-15)
272
+
273
+ U, CS, Vh = linalg.cossin(X, compute_u=False, **kwargs)
274
+ assert U.shape == (0, 0)
275
+ assert_allclose(CS, CS0, rtol=1e-15)
276
+ assert_allclose(Vh, Vh0, rtol=1e-15)
277
+
278
+ # `compute_vh=False`
279
+ u, cs, vh = linalg.cossin(X, separate=True, compute_vh=False, **kwargs)
280
+ assert_allclose(u[0], u[0], rtol=1e-15)
281
+ assert_allclose(u[1], u[1], rtol=1e-15)
282
+ assert_allclose(cs, cs0, rtol=1e-15)
283
+ assert vh[0].shape == (0, 0)
284
+ assert vh[1].shape == (0, 0)
285
+
286
+ U, CS, Vh = linalg.cossin(X, compute_vh=False, **kwargs)
287
+ assert_allclose(U, U0, rtol=1e-15)
288
+ assert_allclose(CS, CS0, rtol=1e-15)
289
+ assert Vh.shape == (0, 0)
290
+
291
+ # `compute_u=False, compute_vh=False`
292
+ u, cs, vh = linalg.cossin(X, separate=True, compute_u=False,
293
+ compute_vh=False, **kwargs)
294
+ assert u[0].shape == (0, 0)
295
+ assert u[1].shape == (0, 0)
296
+ assert_allclose(cs, cs0, rtol=1e-15)
297
+ assert vh[0].shape == (0, 0)
298
+ assert vh[1].shape == (0, 0)
299
+
300
+ U, CS, Vh = linalg.cossin(X, compute_u=False, compute_vh=False, **kwargs)
301
+ assert U.shape == (0, 0)
302
+ assert_allclose(CS, CS0, rtol=1e-15)
303
+ assert Vh.shape == (0, 0)
304
+
305
+
306
+ def test_indexing_bug_gh19365():
307
+ # Regression test for gh-19365, which reported a bug with `separate=False`
308
+ rng = np.random.default_rng(32954827234421)
309
+ m = rng.integers(50, high=100)
310
+ p = rng.integers(10, 40) # always p < m
311
+ q = rng.integers(m - p + 1, m - 1) # always m-p < q < m
312
+ X = unitary_group.rvs(m, random_state=rng) # random unitary matrix
313
+ U, D, Vt = linalg.cossin(X, p=p, q=q, separate=False)
314
+ assert np.allclose(U @ D @ Vt, X)
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_ldl.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy.testing import assert_array_almost_equal, assert_allclose, assert_
3
+ from numpy import (array, eye, zeros, empty_like, empty, tril_indices_from,
4
+ tril, triu_indices_from, spacing, float32, float64,
5
+ complex64, complex128)
6
+ from numpy.exceptions import ComplexWarning
7
+ from scipy.linalg import ldl
8
+ import pytest
9
+
10
+
11
+ def test_args():
12
+ A = eye(3)
13
+ # Nonsquare array
14
+ with pytest.raises(ValueError):
15
+ ldl(A[:, :2])
16
+ # Complex matrix with imaginary diagonal entries with "hermitian=True"
17
+ with pytest.warns(ComplexWarning):
18
+ ldl(A*1j)
19
+
20
+
21
+ def test_empty_array():
22
+ a = empty((0, 0), dtype=complex)
23
+ l, d, p = ldl(empty((0, 0)))
24
+ assert_array_almost_equal(l, empty_like(a))
25
+ assert_array_almost_equal(d, empty_like(a))
26
+ assert_array_almost_equal(p, array([], dtype=int))
27
+
28
+
29
+ def test_simple():
30
+ a = array([[-0.39-0.71j, 5.14-0.64j, -7.86-2.96j, 3.80+0.92j],
31
+ [5.14-0.64j, 8.86+1.81j, -3.52+0.58j, 5.32-1.59j],
32
+ [-7.86-2.96j, -3.52+0.58j, -2.83-0.03j, -1.54-2.86j],
33
+ [3.80+0.92j, 5.32-1.59j, -1.54-2.86j, -0.56+0.12j]])
34
+ b = array([[5., 10, 1, 18],
35
+ [10., 2, 11, 1],
36
+ [1., 11, 19, 9],
37
+ [18., 1, 9, 0]])
38
+ c = array([[52., 97, 112, 107, 50],
39
+ [97., 114, 89, 98, 13],
40
+ [112., 89, 64, 33, 6],
41
+ [107., 98, 33, 60, 73],
42
+ [50., 13, 6, 73, 77]])
43
+
44
+ d = array([[2., 2, -4, 0, 4],
45
+ [2., -2, -2, 10, -8],
46
+ [-4., -2, 6, -8, -4],
47
+ [0., 10, -8, 6, -6],
48
+ [4., -8, -4, -6, 10]])
49
+ e = array([[-1.36+0.00j, 0+0j, 0+0j, 0+0j],
50
+ [1.58-0.90j, -8.87+0j, 0+0j, 0+0j],
51
+ [2.21+0.21j, -1.84+0.03j, -4.63+0j, 0+0j],
52
+ [3.91-1.50j, -1.78-1.18j, 0.11-0.11j, -1.84+0.00j]])
53
+ for x in (b, c, d):
54
+ l, d, p = ldl(x)
55
+ assert_allclose(l.dot(d).dot(l.T), x, atol=spacing(1000.), rtol=0)
56
+
57
+ u, d, p = ldl(x, lower=False)
58
+ assert_allclose(u.dot(d).dot(u.T), x, atol=spacing(1000.), rtol=0)
59
+
60
+ l, d, p = ldl(a, hermitian=False)
61
+ assert_allclose(l.dot(d).dot(l.T), a, atol=spacing(1000.), rtol=0)
62
+
63
+ u, d, p = ldl(a, lower=False, hermitian=False)
64
+ assert_allclose(u.dot(d).dot(u.T), a, atol=spacing(1000.), rtol=0)
65
+
66
+ # Use upper part for the computation and use the lower part for comparison
67
+ l, d, p = ldl(e.conj().T, lower=0)
68
+ assert_allclose(tril(l.dot(d).dot(l.conj().T)-e), zeros((4, 4)),
69
+ atol=spacing(1000.), rtol=0)
70
+
71
+
72
+ def test_permutations():
73
+ rng = np.random.default_rng(1234)
74
+ for _ in range(10):
75
+ n = rng.integers(1, 100)
76
+ # Random real/complex array
77
+ x = rng.random((n, n)) + 0 if rng.integers(2) else rng.random((n, n))*1j
78
+ x = x + x.conj().T
79
+ x += eye(n)*rng.integers(5, 1e6)
80
+ l_ind = tril_indices_from(x, k=-1)
81
+ u_ind = triu_indices_from(x, k=1)
82
+
83
+ # Test whether permutations lead to a triangular array
84
+ u, d, p = ldl(x, lower=0)
85
+ # lower part should be zero
86
+ assert_(not any(u[p, :][l_ind]), f'Spin {_} failed')
87
+
88
+ l, d, p = ldl(x, lower=1)
89
+ # upper part should be zero
90
+ assert_(not any(l[p, :][u_ind]), f'Spin {_} failed')
91
+
92
+
93
+ @pytest.mark.parametrize("dtype", [float32, float64])
94
+ @pytest.mark.parametrize("n", [30, 150])
95
+ def test_ldl_type_size_combinations_real(n, dtype):
96
+ rng = np.random.default_rng(1234)
97
+ msg = (f"Failed for size: {n}, dtype: {dtype}")
98
+
99
+ x = rng.random((n, n)).astype(dtype)
100
+ x = x + x.T
101
+ x += eye(n, dtype=dtype)*dtype(rng.integers(5, 1e6))
102
+
103
+ l, d1, p = ldl(x)
104
+ u, d2, p = ldl(x, lower=0)
105
+ rtol = 1e-4 if dtype is float32 else 1e-10
106
+ assert_allclose(l.dot(d1).dot(l.T), x, rtol=rtol, err_msg=msg)
107
+ assert_allclose(u.dot(d2).dot(u.T), x, rtol=rtol, err_msg=msg)
108
+
109
+
110
+ @pytest.mark.parametrize("dtype", [complex64, complex128])
111
+ @pytest.mark.parametrize("n", [30, 150])
112
+ def test_ldl_type_size_combinations_complex(n, dtype):
113
+ rng = np.random.default_rng(1234)
114
+ msg1 = (f"Her failed for size: {n}, dtype: {dtype}")
115
+ msg2 = (f"Sym failed for size: {n}, dtype: {dtype}")
116
+
117
+ # Complex hermitian upper/lower
118
+ x = (rng.random((n, n))+1j*rng.random((n, n))).astype(dtype)
119
+ x = x+x.conj().T
120
+ x += eye(n, dtype=dtype)*dtype(rng.integers(5, 1e6))
121
+
122
+ l, d1, p = ldl(x)
123
+ u, d2, p = ldl(x, lower=0)
124
+ rtol = 2e-4 if dtype is complex64 else 1e-10
125
+ assert_allclose(l.dot(d1).dot(l.conj().T), x, rtol=rtol, err_msg=msg1)
126
+ assert_allclose(u.dot(d2).dot(u.conj().T), x, rtol=rtol, err_msg=msg1)
127
+
128
+ # Complex symmetric upper/lower
129
+ x = (rng.random((n, n))+1j*rng.random((n, n))).astype(dtype)
130
+ x = x+x.T
131
+ x += eye(n, dtype=dtype)*dtype(rng.integers(5, 1e6))
132
+
133
+ l, d1, p = ldl(x, hermitian=0)
134
+ u, d2, p = ldl(x, lower=0, hermitian=0)
135
+ assert_allclose(l.dot(d1).dot(l.T), x, rtol=rtol, err_msg=msg2)
136
+ assert_allclose(u.dot(d2).dot(u.T), x, rtol=rtol, err_msg=msg2)
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_lu.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from pytest import raises as assert_raises
3
+
4
+ import numpy as np
5
+ from scipy.linalg import lu, lu_factor, lu_solve, get_lapack_funcs, solve
6
+ from numpy.testing import assert_allclose, assert_array_equal, assert_equal
7
+ from scipy.linalg.lapack import HAS_ILP64
8
+
9
+
10
+ REAL_DTYPES = [np.float32, np.float64]
11
+ COMPLEX_DTYPES = [np.complex64, np.complex128]
12
+ DTYPES = REAL_DTYPES + COMPLEX_DTYPES
13
+
14
+
15
+ class TestLU:
16
+ def setup_method(self):
17
+ self.rng = np.random.default_rng(1682281250228846)
18
+
19
+ def test_old_lu_smoke_tests(self):
20
+ "Tests from old fortran based lu test suite"
21
+ a = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]])
22
+ p, l, u = lu(a)
23
+ result_lu = np.array([[2., 5., 6.], [0.5, -0.5, 0.], [0.5, 1., 0.]])
24
+ assert_allclose(p, np.rot90(np.eye(3)))
25
+ assert_allclose(l, np.tril(result_lu, k=-1)+np.eye(3))
26
+ assert_allclose(u, np.triu(result_lu))
27
+
28
+ a = np.array([[1, 2, 3], [1, 2, 3], [2, 5j, 6]])
29
+ p, l, u = lu(a)
30
+ result_lu = np.array([[2., 5.j, 6.], [0.5, 2-2.5j, 0.], [0.5, 1., 0.]])
31
+ assert_allclose(p, np.rot90(np.eye(3)))
32
+ assert_allclose(l, np.tril(result_lu, k=-1)+np.eye(3))
33
+ assert_allclose(u, np.triu(result_lu))
34
+
35
+ b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
36
+ p, l, u = lu(b)
37
+ assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]))
38
+ assert_allclose(l, np.array([[1, 0, 0], [1/7, 1, 0], [4/7, 0.5, 1]]))
39
+ assert_allclose(u, np.array([[7, 8, 9], [0, 6/7, 12/7], [0, 0, 0]]),
40
+ rtol=0., atol=1e-14)
41
+
42
+ cb = np.array([[1.j, 2.j, 3.j], [4j, 5j, 6j], [7j, 8j, 9j]])
43
+ p, l, u = lu(cb)
44
+ assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]))
45
+ assert_allclose(l, np.array([[1, 0, 0], [1/7, 1, 0], [4/7, 0.5, 1]]))
46
+ assert_allclose(u, np.array([[7, 8, 9], [0, 6/7, 12/7], [0, 0, 0]])*1j,
47
+ rtol=0., atol=1e-14)
48
+
49
+ # Rectangular matrices
50
+ hrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]])
51
+ p, l, u = lu(hrect)
52
+ assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]))
53
+ assert_allclose(l, np.array([[1, 0, 0], [1/9, 1, 0], [5/9, 0.5, 1]]))
54
+ assert_allclose(u, np.array([[9, 10, 12, 12], [0, 8/9, 15/9, 24/9],
55
+ [0, 0, -0.5, 0]]), rtol=0., atol=1e-14)
56
+
57
+ chrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]])*1.j
58
+ p, l, u = lu(chrect)
59
+ assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]))
60
+ assert_allclose(l, np.array([[1, 0, 0], [1/9, 1, 0], [5/9, 0.5, 1]]))
61
+ assert_allclose(u, np.array([[9, 10, 12, 12], [0, 8/9, 15/9, 24/9],
62
+ [0, 0, -0.5, 0]])*1j, rtol=0., atol=1e-14)
63
+
64
+ vrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]])
65
+ p, l, u = lu(vrect)
66
+ assert_allclose(p, np.eye(4)[[1, 3, 2, 0], :])
67
+ assert_allclose(l, np.array([[1., 0, 0], [0.1, 1, 0], [0.7, -0.5, 1],
68
+ [0.4, 0.25, 0.5]]))
69
+ assert_allclose(u, np.array([[10, 12, 12],
70
+ [0, 0.8, 1.8],
71
+ [0, 0, 1.5]]))
72
+
73
+ cvrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]])*1j
74
+ p, l, u = lu(cvrect)
75
+ assert_allclose(p, np.eye(4)[[1, 3, 2, 0], :])
76
+ assert_allclose(l, np.array([[1., 0, 0],
77
+ [0.1, 1, 0],
78
+ [0.7, -0.5, 1],
79
+ [0.4, 0.25, 0.5]]))
80
+ assert_allclose(u, np.array([[10, 12, 12],
81
+ [0, 0.8, 1.8],
82
+ [0, 0, 1.5]])*1j)
83
+
84
+ @pytest.mark.parametrize('shape', [[2, 2], [2, 4], [4, 2], [20, 20],
85
+ [20, 4], [4, 20], [3, 2, 9, 9],
86
+ [2, 2, 17, 5], [2, 2, 11, 7]])
87
+ def test_simple_lu_shapes_real_complex(self, shape):
88
+ a = self.rng.uniform(-10., 10., size=shape)
89
+ p, l, u = lu(a)
90
+ assert_allclose(a, p @ l @ u)
91
+ pl, u = lu(a, permute_l=True)
92
+ assert_allclose(a, pl @ u)
93
+
94
+ b = self.rng.uniform(-10., 10., size=shape)*1j
95
+ b += self.rng.uniform(-10, 10, size=shape)
96
+ pl, u = lu(b, permute_l=True)
97
+ assert_allclose(b, pl @ u)
98
+
99
+ @pytest.mark.parametrize('shape', [[2, 2], [2, 4], [4, 2], [20, 20],
100
+ [20, 4], [4, 20]])
101
+ def test_simple_lu_shapes_real_complex_2d_indices(self, shape):
102
+ a = self.rng.uniform(-10., 10., size=shape)
103
+ p, l, u = lu(a, p_indices=True)
104
+ assert_allclose(a, l[p, :] @ u)
105
+
106
+ def test_1by1_input_output(self):
107
+ a = self.rng.random([4, 5, 1, 1], dtype=np.float32)
108
+ p, l, u = lu(a, p_indices=True)
109
+ assert_allclose(p, np.zeros(shape=(4, 5, 1), dtype=int))
110
+ assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.float32))
111
+ assert_allclose(u, a)
112
+
113
+ a = self.rng.random([4, 5, 1, 1], dtype=np.float32)
114
+ p, l, u = lu(a)
115
+ assert_allclose(p, np.ones(shape=(4, 5, 1, 1), dtype=np.float32))
116
+ assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.float32))
117
+ assert_allclose(u, a)
118
+
119
+ pl, u = lu(a, permute_l=True)
120
+ assert_allclose(pl, np.ones(shape=(4, 5, 1, 1), dtype=np.float32))
121
+ assert_allclose(u, a)
122
+
123
+ a = self.rng.random([4, 5, 1, 1], dtype=np.float32)*np.complex64(1.j)
124
+ p, l, u = lu(a)
125
+ assert_allclose(p, np.ones(shape=(4, 5, 1, 1), dtype=np.complex64))
126
+ assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.complex64))
127
+ assert_allclose(u, a)
128
+
129
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
130
+ def test_empty_edge_cases(self):
131
+ a = np.empty([0, 0])
132
+ p, l, u = lu(a)
133
+ assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float64))
134
+ assert_allclose(l, np.empty(shape=(0, 0), dtype=np.float64))
135
+ assert_allclose(u, np.empty(shape=(0, 0), dtype=np.float64))
136
+
137
+ a = np.empty([0, 3], dtype=np.float16)
138
+ p, l, u = lu(a)
139
+ assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float32))
140
+ assert_allclose(l, np.empty(shape=(0, 0), dtype=np.float32))
141
+ assert_allclose(u, np.empty(shape=(0, 3), dtype=np.float32))
142
+
143
+ a = np.empty([3, 0], dtype=np.complex64)
144
+ p, l, u = lu(a)
145
+ assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float32))
146
+ assert_allclose(l, np.empty(shape=(3, 0), dtype=np.complex64))
147
+ assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64))
148
+ p, l, u = lu(a, p_indices=True)
149
+ assert_allclose(p, np.empty(shape=(0,), dtype=int))
150
+ assert_allclose(l, np.empty(shape=(3, 0), dtype=np.complex64))
151
+ assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64))
152
+ pl, u = lu(a, permute_l=True)
153
+ assert_allclose(pl, np.empty(shape=(3, 0), dtype=np.complex64))
154
+ assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64))
155
+
156
+ a = np.empty([3, 0, 0], dtype=np.complex64)
157
+ p, l, u = lu(a)
158
+ assert_allclose(p, np.empty(shape=(3, 0, 0), dtype=np.float32))
159
+ assert_allclose(l, np.empty(shape=(3, 0, 0), dtype=np.complex64))
160
+ assert_allclose(u, np.empty(shape=(3, 0, 0), dtype=np.complex64))
161
+
162
+ a = np.empty([0, 0, 3])
163
+ p, l, u = lu(a)
164
+ assert_allclose(p, np.empty(shape=(0, 0, 0)))
165
+ assert_allclose(l, np.empty(shape=(0, 0, 0)))
166
+ assert_allclose(u, np.empty(shape=(0, 0, 3)))
167
+
168
+ with assert_raises(ValueError, match='at least two-dimensional'):
169
+ lu(np.array([]))
170
+
171
+ a = np.array([[]])
172
+ p, l, u = lu(a)
173
+ assert_allclose(p, np.empty(shape=(0, 0)))
174
+ assert_allclose(l, np.empty(shape=(1, 0)))
175
+ assert_allclose(u, np.empty(shape=(0, 0)))
176
+
177
+ a = np.array([[[]]])
178
+ p, l, u = lu(a)
179
+ assert_allclose(p, np.empty(shape=(1, 0, 0)))
180
+ assert_allclose(l, np.empty(shape=(1, 1, 0)))
181
+ assert_allclose(u, np.empty(shape=(1, 0, 0)))
182
+
183
+
184
+ class TestLUFactor:
185
+ def setup_method(self):
186
+ self.rng = np.random.default_rng(1682281250228846)
187
+
188
+ self.a = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]])
189
+ self.ca = np.array([[1, 2, 3], [1, 2, 3], [2, 5j, 6]])
190
+ # Those matrices are more robust to detect problems in permutation
191
+ # matrices than the ones above
192
+ self.b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
193
+ self.cb = np.array([[1j, 2j, 3j], [4j, 5j, 6j], [7j, 8j, 9j]])
194
+
195
+ # Rectangular matrices
196
+ self.hrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]])
197
+ self.chrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8],
198
+ [9, 10, 12, 12]]) * 1.j
199
+
200
+ self.vrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]])
201
+ self.cvrect = 1.j * np.array([[1, 2, 3],
202
+ [4, 5, 6],
203
+ [7, 8, 9],
204
+ [10, 12, 12]])
205
+
206
+ # Medium sizes matrices
207
+ self.med = self.rng.random((30, 40))
208
+ self.cmed = self.rng.random((30, 40)) + 1.j*self.rng.random((30, 40))
209
+
210
+ def _test_common_lu_factor(self, data):
211
+ l_and_u1, piv1 = lu_factor(data)
212
+ (getrf,) = get_lapack_funcs(("getrf",), (data,))
213
+ l_and_u2, piv2, _ = getrf(data, overwrite_a=False)
214
+ assert_allclose(l_and_u1, l_and_u2)
215
+ assert_allclose(piv1, piv2)
216
+
217
+ # Simple tests.
218
+ # For lu_factor gives a LinAlgWarning because these matrices are singular
219
+ def test_hrectangular(self):
220
+ self._test_common_lu_factor(self.hrect)
221
+
222
+ def test_vrectangular(self):
223
+ self._test_common_lu_factor(self.vrect)
224
+
225
+ def test_hrectangular_complex(self):
226
+ self._test_common_lu_factor(self.chrect)
227
+
228
+ def test_vrectangular_complex(self):
229
+ self._test_common_lu_factor(self.cvrect)
230
+
231
+ # Bigger matrices
232
+ def test_medium1(self):
233
+ """Check lu decomposition on medium size, rectangular matrix."""
234
+ self._test_common_lu_factor(self.med)
235
+
236
+ def test_medium1_complex(self):
237
+ """Check lu decomposition on medium size, rectangular matrix."""
238
+ self._test_common_lu_factor(self.cmed)
239
+
240
+ def test_check_finite(self):
241
+ p, l, u = lu(self.a, check_finite=False)
242
+ assert_allclose(p @ l @ u, self.a)
243
+
244
+ def test_simple_known(self):
245
+ # Ticket #1458
246
+ for order in ['C', 'F']:
247
+ A = np.array([[2, 1], [0, 1.]], order=order)
248
+ LU, P = lu_factor(A)
249
+ assert_allclose(LU, np.array([[2, 1], [0, 1]]))
250
+ assert_array_equal(P, np.array([0, 1]))
251
+
252
+ @pytest.mark.parametrize("m", [0, 1, 2])
253
+ @pytest.mark.parametrize("n", [0, 1, 2])
254
+ @pytest.mark.parametrize('dtype', DTYPES)
255
+ def test_shape_dtype(self, m, n, dtype):
256
+ k = min(m, n)
257
+
258
+ a = np.eye(m, n, dtype=dtype)
259
+ lu, p = lu_factor(a)
260
+ assert_equal(lu.shape, (m, n))
261
+ assert_equal(lu.dtype, dtype)
262
+ assert_equal(p.shape, (k,))
263
+ assert_equal(p.dtype, np.int64 if HAS_ILP64 else np.int32)
264
+
265
+ @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)])
266
+ def test_empty(self, m, n):
267
+ a = np.zeros((m, n))
268
+ lu, p = lu_factor(a)
269
+ assert_allclose(lu, np.empty((m, n)))
270
+ assert_allclose(p, np.arange(0))
271
+
272
+
273
+ class TestLUSolve:
274
+ def setup_method(self):
275
+ self.rng = np.random.default_rng(1682281250228846)
276
+
277
+ def test_lu(self):
278
+ a0 = self.rng.random((10, 10))
279
+ b = self.rng.random((10,))
280
+
281
+ for order in ['C', 'F']:
282
+ a = np.array(a0, order=order)
283
+ x1 = solve(a, b)
284
+ lu_a = lu_factor(a)
285
+ x2 = lu_solve(lu_a, b)
286
+ assert_allclose(x1, x2)
287
+
288
+ def test_check_finite(self):
289
+ a = self.rng.random((10, 10))
290
+ b = self.rng.random((10,))
291
+ x1 = solve(a, b)
292
+ lu_a = lu_factor(a, check_finite=False)
293
+ x2 = lu_solve(lu_a, b, check_finite=False)
294
+ assert_allclose(x1, x2)
295
+
296
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
297
+ @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
298
+ def test_empty(self, dt, dt_b):
299
+ lu_and_piv = (np.empty((0, 0), dtype=dt), np.array([]))
300
+ b = np.asarray([], dtype=dt_b)
301
+ x = lu_solve(lu_and_piv, b)
302
+ assert x.shape == (0,)
303
+
304
+ m = lu_solve((np.eye(2, dtype=dt), [0, 1]), np.ones(2, dtype=dt_b))
305
+ assert x.dtype == m.dtype
306
+
307
+ b = np.empty((0, 0), dtype=dt_b)
308
+ x = lu_solve(lu_and_piv, b)
309
+ assert x.shape == (0, 0)
310
+ assert x.dtype == m.dtype
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_polar.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import numpy as np
3
+ from numpy.linalg import norm
4
+ from numpy.testing import (assert_, assert_allclose, assert_equal)
5
+ from scipy.linalg import polar, eigh
6
+
7
+
8
+ diag2 = np.array([[2, 0], [0, 3]])
9
+ a13 = np.array([[1, 2, 2]])
10
+
11
+ precomputed_cases = [
12
+ [[[0]], 'right', [[1]], [[0]]],
13
+ [[[0]], 'left', [[1]], [[0]]],
14
+ [[[9]], 'right', [[1]], [[9]]],
15
+ [[[9]], 'left', [[1]], [[9]]],
16
+ [diag2, 'right', np.eye(2), diag2],
17
+ [diag2, 'left', np.eye(2), diag2],
18
+ [a13, 'right', a13/norm(a13[0]), a13.T.dot(a13)/norm(a13[0])],
19
+ ]
20
+
21
+ verify_cases = [
22
+ [[1, 2], [3, 4]],
23
+ [[1, 2, 3]],
24
+ [[1], [2], [3]],
25
+ [[1, 2, 3], [3, 4, 0]],
26
+ [[1, 2], [3, 4], [5, 5]],
27
+ [[1, 2], [3, 4+5j]],
28
+ [[1, 2, 3j]],
29
+ [[1], [2], [3j]],
30
+ [[1, 2, 3+2j], [3, 4-1j, -4j]],
31
+ [[1, 2], [3-2j, 4+0.5j], [5, 5]],
32
+ [[10000, 10, 1], [-1, 2, 3j], [0, 1, 2]],
33
+ np.empty((0, 0)),
34
+ np.empty((0, 2)),
35
+ np.empty((2, 0)),
36
+ ]
37
+
38
+
39
+ def check_precomputed_polar(a, side, expected_u, expected_p):
40
+ # Compare the result of the polar decomposition to a
41
+ # precomputed result.
42
+ u, p = polar(a, side=side)
43
+ assert_allclose(u, expected_u, atol=1e-15)
44
+ assert_allclose(p, expected_p, atol=1e-15)
45
+
46
+
47
+ def verify_polar(a):
48
+ # Compute the polar decomposition, and then verify that
49
+ # the result has all the expected properties.
50
+ product_atol = np.sqrt(np.finfo(float).eps)
51
+
52
+ aa = np.asarray(a)
53
+ m, n = aa.shape
54
+
55
+ u, p = polar(a, side='right')
56
+ assert_equal(u.shape, (m, n))
57
+ assert_equal(p.shape, (n, n))
58
+ # a = up
59
+ assert_allclose(u.dot(p), a, atol=product_atol)
60
+ if m >= n:
61
+ assert_allclose(u.conj().T.dot(u), np.eye(n), atol=1e-15)
62
+ else:
63
+ assert_allclose(u.dot(u.conj().T), np.eye(m), atol=1e-15)
64
+ # p is Hermitian positive semidefinite.
65
+ assert_allclose(p.conj().T, p)
66
+ evals = eigh(p, eigvals_only=True)
67
+ nonzero_evals = evals[abs(evals) > 1e-14]
68
+ assert_((nonzero_evals >= 0).all())
69
+
70
+ u, p = polar(a, side='left')
71
+ assert_equal(u.shape, (m, n))
72
+ assert_equal(p.shape, (m, m))
73
+ # a = pu
74
+ assert_allclose(p.dot(u), a, atol=product_atol)
75
+ if m >= n:
76
+ assert_allclose(u.conj().T.dot(u), np.eye(n), atol=1e-15)
77
+ else:
78
+ assert_allclose(u.dot(u.conj().T), np.eye(m), atol=1e-15)
79
+ # p is Hermitian positive semidefinite.
80
+ assert_allclose(p.conj().T, p)
81
+ evals = eigh(p, eigvals_only=True)
82
+ nonzero_evals = evals[abs(evals) > 1e-14]
83
+ assert_((nonzero_evals >= 0).all())
84
+
85
+
86
+ def test_precomputed_cases():
87
+ for a, side, expected_u, expected_p in precomputed_cases:
88
+ check_precomputed_polar(a, side, expected_u, expected_p)
89
+
90
+
91
+ def test_verify_cases():
92
+ for a in verify_cases:
93
+ verify_polar(a)
94
+
95
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
96
+ @pytest.mark.parametrize('shape', [(0, 0), (0, 2), (2, 0)])
97
+ @pytest.mark.parametrize('side', ['left', 'right'])
98
+ def test_empty(dt, shape, side):
99
+ a = np.empty(shape, dtype=dt)
100
+ m, n = shape
101
+ p_shape = (m, m) if side == 'left' else (n, n)
102
+
103
+ u, p = polar(a, side=side)
104
+ u_n, p_n = polar(np.eye(5, dtype=dt))
105
+
106
+ assert_equal(u.dtype, u_n.dtype)
107
+ assert_equal(p.dtype, p_n.dtype)
108
+ assert u.shape == shape
109
+ assert p.shape == p_shape
110
+ assert np.all(p == 0)
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_update.py ADDED
@@ -0,0 +1,1704 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import pytest
3
+
4
+ import numpy as np
5
+ from numpy.testing import assert_, assert_allclose, assert_equal
6
+ from pytest import raises as assert_raises
7
+ from scipy import linalg
8
+ import scipy.linalg._decomp_update as _decomp_update
9
+ from scipy.linalg._decomp_update import qr_delete, qr_update, qr_insert
10
+
11
+ def assert_unitary(a, rtol=None, atol=None, assert_sqr=True):
12
+ if rtol is None:
13
+ rtol = 10.0 ** -(np.finfo(a.dtype).precision-2)
14
+ if atol is None:
15
+ atol = 10*np.finfo(a.dtype).eps
16
+
17
+ if assert_sqr:
18
+ assert_(a.shape[0] == a.shape[1], 'unitary matrices must be square')
19
+ aTa = np.dot(a.T.conj(), a)
20
+ assert_allclose(aTa, np.eye(a.shape[1]), rtol=rtol, atol=atol)
21
+
22
+ def assert_upper_tri(a, rtol=None, atol=None):
23
+ if rtol is None:
24
+ rtol = 10.0 ** -(np.finfo(a.dtype).precision-2)
25
+ if atol is None:
26
+ atol = 2*np.finfo(a.dtype).eps
27
+ mask = np.tri(a.shape[0], a.shape[1], -1, np.bool_)
28
+ assert_allclose(a[mask], 0.0, rtol=rtol, atol=atol)
29
+
30
+ def check_qr(q, r, a, rtol, atol, assert_sqr=True):
31
+ assert_unitary(q, rtol, atol, assert_sqr)
32
+ assert_upper_tri(r, rtol, atol)
33
+ assert_allclose(q.dot(r), a, rtol=rtol, atol=atol)
34
+
35
+ def make_strided(arrs):
36
+ strides = [(3, 7), (2, 2), (3, 4), (4, 2), (5, 4), (2, 3), (2, 1), (4, 5)]
37
+ kmax = len(strides)
38
+ k = 0
39
+ ret = []
40
+ for a in arrs:
41
+ if a.ndim == 1:
42
+ s = strides[k % kmax]
43
+ k += 1
44
+ base = np.zeros(s[0]*a.shape[0]+s[1], a.dtype)
45
+ view = base[s[1]::s[0]]
46
+ view[...] = a
47
+ elif a.ndim == 2:
48
+ s = strides[k % kmax]
49
+ t = strides[(k+1) % kmax]
50
+ k += 2
51
+ base = np.zeros((s[0]*a.shape[0]+s[1], t[0]*a.shape[1]+t[1]),
52
+ a.dtype)
53
+ view = base[s[1]::s[0], t[1]::t[0]]
54
+ view[...] = a
55
+ else:
56
+ raise ValueError('make_strided only works for ndim = 1 or'
57
+ ' 2 arrays')
58
+ ret.append(view)
59
+ return ret
60
+
61
+ def negate_strides(arrs):
62
+ ret = []
63
+ for a in arrs:
64
+ b = np.zeros_like(a)
65
+ if b.ndim == 2:
66
+ b = b[::-1, ::-1]
67
+ elif b.ndim == 1:
68
+ b = b[::-1]
69
+ else:
70
+ raise ValueError('negate_strides only works for ndim = 1 or'
71
+ ' 2 arrays')
72
+ b[...] = a
73
+ ret.append(b)
74
+ return ret
75
+
76
+ def nonitemsize_strides(arrs):
77
+ out = []
78
+ for a in arrs:
79
+ a_dtype = a.dtype
80
+ b = np.zeros(a.shape, [('a', a_dtype), ('junk', 'S1')])
81
+ c = b.getfield(a_dtype)
82
+ c[...] = a
83
+ out.append(c)
84
+ return out
85
+
86
+
87
+ def make_nonnative(arrs):
88
+ return [a.astype(a.dtype.newbyteorder()) for a in arrs]
89
+
90
+
91
+ class BaseQRdeltas:
92
+ def setup_method(self):
93
+ self.rtol = 10.0 ** -(np.finfo(self.dtype).precision-2)
94
+ self.atol = 10 * np.finfo(self.dtype).eps
95
+
96
+ def generate(self, type, mode='full'):
97
+ rng = np.random.default_rng(29382)
98
+ shape = {'sqr': (8, 8), 'tall': (12, 7), 'fat': (7, 12),
99
+ 'Mx1': (8, 1), '1xN': (1, 8), '1x1': (1, 1)}[type]
100
+ a = rng.random(shape)
101
+ if np.iscomplexobj(self.dtype.type(1)):
102
+ b = rng.random(shape)
103
+ a = a + 1j * b
104
+ a = a.astype(self.dtype)
105
+ q, r = linalg.qr(a, mode=mode)
106
+ return a, q, r
107
+
108
+ class BaseQRdelete(BaseQRdeltas):
109
+ def test_sqr_1_row(self):
110
+ a, q, r = self.generate('sqr')
111
+ for row in range(r.shape[0]):
112
+ q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
113
+ a1 = np.delete(a, row, 0)
114
+ check_qr(q1, r1, a1, self.rtol, self.atol)
115
+
116
+ def test_sqr_p_row(self):
117
+ a, q, r = self.generate('sqr')
118
+ for ndel in range(2, 6):
119
+ for row in range(a.shape[0]-ndel):
120
+ q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
121
+ a1 = np.delete(a, slice(row, row+ndel), 0)
122
+ check_qr(q1, r1, a1, self.rtol, self.atol)
123
+
124
+ def test_sqr_1_col(self):
125
+ a, q, r = self.generate('sqr')
126
+ for col in range(r.shape[1]):
127
+ q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
128
+ a1 = np.delete(a, col, 1)
129
+ check_qr(q1, r1, a1, self.rtol, self.atol)
130
+
131
+ def test_sqr_p_col(self):
132
+ a, q, r = self.generate('sqr')
133
+ for ndel in range(2, 6):
134
+ for col in range(r.shape[1]-ndel):
135
+ q1, r1 = qr_delete(q, r, col, ndel, which='col',
136
+ overwrite_qr=False)
137
+ a1 = np.delete(a, slice(col, col+ndel), 1)
138
+ check_qr(q1, r1, a1, self.rtol, self.atol)
139
+
140
+ def test_tall_1_row(self):
141
+ a, q, r = self.generate('tall')
142
+ for row in range(r.shape[0]):
143
+ q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
144
+ a1 = np.delete(a, row, 0)
145
+ check_qr(q1, r1, a1, self.rtol, self.atol)
146
+
147
+ def test_tall_p_row(self):
148
+ a, q, r = self.generate('tall')
149
+ for ndel in range(2, 6):
150
+ for row in range(a.shape[0]-ndel):
151
+ q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
152
+ a1 = np.delete(a, slice(row, row+ndel), 0)
153
+ check_qr(q1, r1, a1, self.rtol, self.atol)
154
+
155
+ def test_tall_1_col(self):
156
+ a, q, r = self.generate('tall')
157
+ for col in range(r.shape[1]):
158
+ q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
159
+ a1 = np.delete(a, col, 1)
160
+ check_qr(q1, r1, a1, self.rtol, self.atol)
161
+
162
+ def test_tall_p_col(self):
163
+ a, q, r = self.generate('tall')
164
+ for ndel in range(2, 6):
165
+ for col in range(r.shape[1]-ndel):
166
+ q1, r1 = qr_delete(q, r, col, ndel, which='col',
167
+ overwrite_qr=False)
168
+ a1 = np.delete(a, slice(col, col+ndel), 1)
169
+ check_qr(q1, r1, a1, self.rtol, self.atol)
170
+
171
+ def test_fat_1_row(self):
172
+ a, q, r = self.generate('fat')
173
+ for row in range(r.shape[0]):
174
+ q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
175
+ a1 = np.delete(a, row, 0)
176
+ check_qr(q1, r1, a1, self.rtol, self.atol)
177
+
178
+ def test_fat_p_row(self):
179
+ a, q, r = self.generate('fat')
180
+ for ndel in range(2, 6):
181
+ for row in range(a.shape[0]-ndel):
182
+ q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
183
+ a1 = np.delete(a, slice(row, row+ndel), 0)
184
+ check_qr(q1, r1, a1, self.rtol, self.atol)
185
+
186
+ def test_fat_1_col(self):
187
+ a, q, r = self.generate('fat')
188
+ for col in range(r.shape[1]):
189
+ q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
190
+ a1 = np.delete(a, col, 1)
191
+ check_qr(q1, r1, a1, self.rtol, self.atol)
192
+
193
+ def test_fat_p_col(self):
194
+ a, q, r = self.generate('fat')
195
+ for ndel in range(2, 6):
196
+ for col in range(r.shape[1]-ndel):
197
+ q1, r1 = qr_delete(q, r, col, ndel, which='col',
198
+ overwrite_qr=False)
199
+ a1 = np.delete(a, slice(col, col+ndel), 1)
200
+ check_qr(q1, r1, a1, self.rtol, self.atol)
201
+
202
+ def test_economic_1_row(self):
203
+ # this test always starts and ends with an economic decomp.
204
+ a, q, r = self.generate('tall', 'economic')
205
+ for row in range(r.shape[0]):
206
+ q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
207
+ a1 = np.delete(a, row, 0)
208
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
209
+
210
+ # for economic row deletes
211
+ # eco - prow = eco
212
+ # eco - prow = sqr
213
+ # eco - prow = fat
214
+ def base_economic_p_row_xxx(self, ndel):
215
+ a, q, r = self.generate('tall', 'economic')
216
+ for row in range(a.shape[0]-ndel):
217
+ q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
218
+ a1 = np.delete(a, slice(row, row+ndel), 0)
219
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
220
+
221
+ def test_economic_p_row_economic(self):
222
+ # (12, 7) - (3, 7) = (9,7) --> stays economic
223
+ self.base_economic_p_row_xxx(3)
224
+
225
+ def test_economic_p_row_sqr(self):
226
+ # (12, 7) - (5, 7) = (7, 7) --> becomes square
227
+ self.base_economic_p_row_xxx(5)
228
+
229
+ def test_economic_p_row_fat(self):
230
+ # (12, 7) - (7,7) = (5, 7) --> becomes fat
231
+ self.base_economic_p_row_xxx(7)
232
+
233
+ def test_economic_1_col(self):
234
+ a, q, r = self.generate('tall', 'economic')
235
+ for col in range(r.shape[1]):
236
+ q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
237
+ a1 = np.delete(a, col, 1)
238
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
239
+
240
+ def test_economic_p_col(self):
241
+ a, q, r = self.generate('tall', 'economic')
242
+ for ndel in range(2, 6):
243
+ for col in range(r.shape[1]-ndel):
244
+ q1, r1 = qr_delete(q, r, col, ndel, which='col',
245
+ overwrite_qr=False)
246
+ a1 = np.delete(a, slice(col, col+ndel), 1)
247
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
248
+
249
+ def test_Mx1_1_row(self):
250
+ a, q, r = self.generate('Mx1')
251
+ for row in range(r.shape[0]):
252
+ q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
253
+ a1 = np.delete(a, row, 0)
254
+ check_qr(q1, r1, a1, self.rtol, self.atol)
255
+
256
+ def test_Mx1_p_row(self):
257
+ a, q, r = self.generate('Mx1')
258
+ for ndel in range(2, 6):
259
+ for row in range(a.shape[0]-ndel):
260
+ q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
261
+ a1 = np.delete(a, slice(row, row+ndel), 0)
262
+ check_qr(q1, r1, a1, self.rtol, self.atol)
263
+
264
+ def test_1xN_1_col(self):
265
+ a, q, r = self.generate('1xN')
266
+ for col in range(r.shape[1]):
267
+ q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
268
+ a1 = np.delete(a, col, 1)
269
+ check_qr(q1, r1, a1, self.rtol, self.atol)
270
+
271
+ def test_1xN_p_col(self):
272
+ a, q, r = self.generate('1xN')
273
+ for ndel in range(2, 6):
274
+ for col in range(r.shape[1]-ndel):
275
+ q1, r1 = qr_delete(q, r, col, ndel, which='col',
276
+ overwrite_qr=False)
277
+ a1 = np.delete(a, slice(col, col+ndel), 1)
278
+ check_qr(q1, r1, a1, self.rtol, self.atol)
279
+
280
+ def test_Mx1_economic_1_row(self):
281
+ a, q, r = self.generate('Mx1', 'economic')
282
+ for row in range(r.shape[0]):
283
+ q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
284
+ a1 = np.delete(a, row, 0)
285
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
286
+
287
+ def test_Mx1_economic_p_row(self):
288
+ a, q, r = self.generate('Mx1', 'economic')
289
+ for ndel in range(2, 6):
290
+ for row in range(a.shape[0]-ndel):
291
+ q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
292
+ a1 = np.delete(a, slice(row, row+ndel), 0)
293
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
294
+
295
+ def test_delete_last_1_row(self):
296
+ # full and eco are the same for 1xN
297
+ a, q, r = self.generate('1xN')
298
+ q1, r1 = qr_delete(q, r, 0, 1, 'row')
299
+ assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
300
+ assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
301
+
302
+ def test_delete_last_p_row(self):
303
+ a, q, r = self.generate('tall', 'full')
304
+ q1, r1 = qr_delete(q, r, 0, a.shape[0], 'row')
305
+ assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
306
+ assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
307
+
308
+ a, q, r = self.generate('tall', 'economic')
309
+ q1, r1 = qr_delete(q, r, 0, a.shape[0], 'row')
310
+ assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
311
+ assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
312
+
313
+ def test_delete_last_1_col(self):
314
+ a, q, r = self.generate('Mx1', 'economic')
315
+ q1, r1 = qr_delete(q, r, 0, 1, 'col')
316
+ assert_equal(q1, np.ndarray(shape=(q.shape[0], 0), dtype=q.dtype))
317
+ assert_equal(r1, np.ndarray(shape=(0, 0), dtype=r.dtype))
318
+
319
+ a, q, r = self.generate('Mx1', 'full')
320
+ q1, r1 = qr_delete(q, r, 0, 1, 'col')
321
+ assert_unitary(q1)
322
+ assert_(q1.dtype == q.dtype)
323
+ assert_(q1.shape == q.shape)
324
+ assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
325
+
326
+ def test_delete_last_p_col(self):
327
+ a, q, r = self.generate('tall', 'full')
328
+ q1, r1 = qr_delete(q, r, 0, a.shape[1], 'col')
329
+ assert_unitary(q1)
330
+ assert_(q1.dtype == q.dtype)
331
+ assert_(q1.shape == q.shape)
332
+ assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
333
+
334
+ a, q, r = self.generate('tall', 'economic')
335
+ q1, r1 = qr_delete(q, r, 0, a.shape[1], 'col')
336
+ assert_equal(q1, np.ndarray(shape=(q.shape[0], 0), dtype=q.dtype))
337
+ assert_equal(r1, np.ndarray(shape=(0, 0), dtype=r.dtype))
338
+
339
+ def test_delete_1x1_row_col(self):
340
+ a, q, r = self.generate('1x1')
341
+ q1, r1 = qr_delete(q, r, 0, 1, 'row')
342
+ assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
343
+ assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
344
+
345
+ a, q, r = self.generate('1x1')
346
+ q1, r1 = qr_delete(q, r, 0, 1, 'col')
347
+ assert_unitary(q1)
348
+ assert_(q1.dtype == q.dtype)
349
+ assert_(q1.shape == q.shape)
350
+ assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
351
+
352
+ # all full qr, row deletes and single column deletes should be able to
353
+ # handle any non negative strides. (only row and column vector
354
+ # operations are used.) p column delete require fortran ordered
355
+ # Q and R and will make a copy as necessary. Economic qr row deletes
356
+ # require a contiguous q.
357
+
358
+ def base_non_simple_strides(self, adjust_strides, ks, p, which,
359
+ overwriteable):
360
+ if which == 'row':
361
+ qind = (slice(p,None), slice(p,None))
362
+ rind = (slice(p,None), slice(None))
363
+ else:
364
+ qind = (slice(None), slice(None))
365
+ rind = (slice(None), slice(None,-p))
366
+
367
+ for type, k in itertools.product(['sqr', 'tall', 'fat'], ks):
368
+ a, q0, r0, = self.generate(type)
369
+ qs, rs = adjust_strides((q0, r0))
370
+ if p == 1:
371
+ a1 = np.delete(a, k, 0 if which == 'row' else 1)
372
+ else:
373
+ s = slice(k,k+p)
374
+ if k < 0:
375
+ s = slice(k, k + p +
376
+ (a.shape[0] if which == 'row' else a.shape[1]))
377
+ a1 = np.delete(a, s, 0 if which == 'row' else 1)
378
+
379
+ # for each variable, q, r we try with it strided and
380
+ # overwrite=False. Then we try with overwrite=True, and make
381
+ # sure that q and r are still overwritten.
382
+
383
+ q = q0.copy('F')
384
+ r = r0.copy('F')
385
+ q1, r1 = qr_delete(qs, r, k, p, which, False)
386
+ check_qr(q1, r1, a1, self.rtol, self.atol)
387
+ q1o, r1o = qr_delete(qs, r, k, p, which, True)
388
+ check_qr(q1o, r1o, a1, self.rtol, self.atol)
389
+ if overwriteable:
390
+ assert_allclose(q1o, qs[qind], rtol=self.rtol, atol=self.atol)
391
+ assert_allclose(r1o, r[rind], rtol=self.rtol, atol=self.atol)
392
+
393
+ q = q0.copy('F')
394
+ r = r0.copy('F')
395
+ q2, r2 = qr_delete(q, rs, k, p, which, False)
396
+ check_qr(q2, r2, a1, self.rtol, self.atol)
397
+ q2o, r2o = qr_delete(q, rs, k, p, which, True)
398
+ check_qr(q2o, r2o, a1, self.rtol, self.atol)
399
+ if overwriteable:
400
+ assert_allclose(q2o, q[qind], rtol=self.rtol, atol=self.atol)
401
+ assert_allclose(r2o, rs[rind], rtol=self.rtol, atol=self.atol)
402
+
403
+ q = q0.copy('F')
404
+ r = r0.copy('F')
405
+ # since some of these were consumed above
406
+ qs, rs = adjust_strides((q, r))
407
+ q3, r3 = qr_delete(qs, rs, k, p, which, False)
408
+ check_qr(q3, r3, a1, self.rtol, self.atol)
409
+ q3o, r3o = qr_delete(qs, rs, k, p, which, True)
410
+ check_qr(q3o, r3o, a1, self.rtol, self.atol)
411
+ if overwriteable:
412
+ assert_allclose(q2o, qs[qind], rtol=self.rtol, atol=self.atol)
413
+ assert_allclose(r3o, rs[rind], rtol=self.rtol, atol=self.atol)
414
+
415
+ def test_non_unit_strides_1_row(self):
416
+ self.base_non_simple_strides(make_strided, [0], 1, 'row', True)
417
+
418
+ def test_non_unit_strides_p_row(self):
419
+ self.base_non_simple_strides(make_strided, [0], 3, 'row', True)
420
+
421
+ def test_non_unit_strides_1_col(self):
422
+ self.base_non_simple_strides(make_strided, [0], 1, 'col', True)
423
+
424
+ def test_non_unit_strides_p_col(self):
425
+ self.base_non_simple_strides(make_strided, [0], 3, 'col', False)
426
+
427
+ def test_neg_strides_1_row(self):
428
+ self.base_non_simple_strides(negate_strides, [0], 1, 'row', False)
429
+
430
+ def test_neg_strides_p_row(self):
431
+ self.base_non_simple_strides(negate_strides, [0], 3, 'row', False)
432
+
433
+ def test_neg_strides_1_col(self):
434
+ self.base_non_simple_strides(negate_strides, [0], 1, 'col', False)
435
+
436
+ def test_neg_strides_p_col(self):
437
+ self.base_non_simple_strides(negate_strides, [0], 3, 'col', False)
438
+
439
+ def test_non_itemize_strides_1_row(self):
440
+ self.base_non_simple_strides(nonitemsize_strides, [0], 1, 'row', False)
441
+
442
+ def test_non_itemize_strides_p_row(self):
443
+ self.base_non_simple_strides(nonitemsize_strides, [0], 3, 'row', False)
444
+
445
+ def test_non_itemize_strides_1_col(self):
446
+ self.base_non_simple_strides(nonitemsize_strides, [0], 1, 'col', False)
447
+
448
+ def test_non_itemize_strides_p_col(self):
449
+ self.base_non_simple_strides(nonitemsize_strides, [0], 3, 'col', False)
450
+
451
+ def test_non_native_byte_order_1_row(self):
452
+ self.base_non_simple_strides(make_nonnative, [0], 1, 'row', False)
453
+
454
+ def test_non_native_byte_order_p_row(self):
455
+ self.base_non_simple_strides(make_nonnative, [0], 3, 'row', False)
456
+
457
+ def test_non_native_byte_order_1_col(self):
458
+ self.base_non_simple_strides(make_nonnative, [0], 1, 'col', False)
459
+
460
+ def test_non_native_byte_order_p_col(self):
461
+ self.base_non_simple_strides(make_nonnative, [0], 3, 'col', False)
462
+
463
+ def test_neg_k(self):
464
+ a, q, r = self.generate('sqr')
465
+ for k, p, w in itertools.product([-3, -7], [1, 3], ['row', 'col']):
466
+ q1, r1 = qr_delete(q, r, k, p, w, overwrite_qr=False)
467
+ if w == 'row':
468
+ a1 = np.delete(a, slice(k+a.shape[0], k+p+a.shape[0]), 0)
469
+ else:
470
+ a1 = np.delete(a, slice(k+a.shape[0], k+p+a.shape[1]), 1)
471
+ check_qr(q1, r1, a1, self.rtol, self.atol)
472
+
473
+ def base_overwrite_qr(self, which, p, test_C, test_F, mode='full'):
474
+ assert_sqr = True if mode == 'full' else False
475
+ if which == 'row':
476
+ qind = (slice(p,None), slice(p,None))
477
+ rind = (slice(p,None), slice(None))
478
+ else:
479
+ qind = (slice(None), slice(None))
480
+ rind = (slice(None), slice(None,-p))
481
+ a, q0, r0 = self.generate('sqr', mode)
482
+ if p == 1:
483
+ a1 = np.delete(a, 3, 0 if which == 'row' else 1)
484
+ else:
485
+ a1 = np.delete(a, slice(3, 3+p), 0 if which == 'row' else 1)
486
+
487
+ # don't overwrite
488
+ q = q0.copy('F')
489
+ r = r0.copy('F')
490
+ q1, r1 = qr_delete(q, r, 3, p, which, False)
491
+ check_qr(q1, r1, a1, self.rtol, self.atol, assert_sqr)
492
+ check_qr(q, r, a, self.rtol, self.atol, assert_sqr)
493
+
494
+ if test_F:
495
+ q = q0.copy('F')
496
+ r = r0.copy('F')
497
+ q2, r2 = qr_delete(q, r, 3, p, which, True)
498
+ check_qr(q2, r2, a1, self.rtol, self.atol, assert_sqr)
499
+ # verify the overwriting
500
+ assert_allclose(q2, q[qind], rtol=self.rtol, atol=self.atol)
501
+ assert_allclose(r2, r[rind], rtol=self.rtol, atol=self.atol)
502
+
503
+ if test_C:
504
+ q = q0.copy('C')
505
+ r = r0.copy('C')
506
+ q3, r3 = qr_delete(q, r, 3, p, which, True)
507
+ check_qr(q3, r3, a1, self.rtol, self.atol, assert_sqr)
508
+ assert_allclose(q3, q[qind], rtol=self.rtol, atol=self.atol)
509
+ assert_allclose(r3, r[rind], rtol=self.rtol, atol=self.atol)
510
+
511
+ def test_overwrite_qr_1_row(self):
512
+ # any positively strided q and r.
513
+ self.base_overwrite_qr('row', 1, True, True)
514
+
515
+ def test_overwrite_economic_qr_1_row(self):
516
+ # Any contiguous q and positively strided r.
517
+ self.base_overwrite_qr('row', 1, True, True, 'economic')
518
+
519
+ def test_overwrite_qr_1_col(self):
520
+ # any positively strided q and r.
521
+ # full and eco share code paths
522
+ self.base_overwrite_qr('col', 1, True, True)
523
+
524
+ def test_overwrite_qr_p_row(self):
525
+ # any positively strided q and r.
526
+ self.base_overwrite_qr('row', 3, True, True)
527
+
528
+ def test_overwrite_economic_qr_p_row(self):
529
+ # any contiguous q and positively strided r
530
+ self.base_overwrite_qr('row', 3, True, True, 'economic')
531
+
532
+ def test_overwrite_qr_p_col(self):
533
+ # only F ordered q and r can be overwritten for cols
534
+ # full and eco share code paths
535
+ self.base_overwrite_qr('col', 3, False, True)
536
+
537
+ def test_bad_which(self):
538
+ a, q, r = self.generate('sqr')
539
+ assert_raises(ValueError, qr_delete, q, r, 0, which='foo')
540
+
541
+ def test_bad_k(self):
542
+ a, q, r = self.generate('tall')
543
+ assert_raises(ValueError, qr_delete, q, r, q.shape[0], 1)
544
+ assert_raises(ValueError, qr_delete, q, r, -q.shape[0]-1, 1)
545
+ assert_raises(ValueError, qr_delete, q, r, r.shape[0], 1, 'col')
546
+ assert_raises(ValueError, qr_delete, q, r, -r.shape[0]-1, 1, 'col')
547
+
548
+ def test_bad_p(self):
549
+ a, q, r = self.generate('tall')
550
+ # p must be positive
551
+ assert_raises(ValueError, qr_delete, q, r, 0, -1)
552
+ assert_raises(ValueError, qr_delete, q, r, 0, -1, 'col')
553
+
554
+ # and nonzero
555
+ assert_raises(ValueError, qr_delete, q, r, 0, 0)
556
+ assert_raises(ValueError, qr_delete, q, r, 0, 0, 'col')
557
+
558
+ # must have at least k+p rows or cols, depending.
559
+ assert_raises(ValueError, qr_delete, q, r, 3, q.shape[0]-2)
560
+ assert_raises(ValueError, qr_delete, q, r, 3, r.shape[1]-2, 'col')
561
+
562
+ def test_empty_q(self):
563
+ a, q, r = self.generate('tall')
564
+ # same code path for 'row' and 'col'
565
+ assert_raises(ValueError, qr_delete, np.array([]), r, 0, 1)
566
+
567
+ def test_empty_r(self):
568
+ a, q, r = self.generate('tall')
569
+ # same code path for 'row' and 'col'
570
+ assert_raises(ValueError, qr_delete, q, np.array([]), 0, 1)
571
+
572
+ def test_mismatched_q_and_r(self):
573
+ a, q, r = self.generate('tall')
574
+ r = r[1:]
575
+ assert_raises(ValueError, qr_delete, q, r, 0, 1)
576
+
577
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
578
+ def test_unsupported_dtypes(self):
579
+ dts = ['int8', 'int16', 'int32', 'int64',
580
+ 'uint8', 'uint16', 'uint32', 'uint64',
581
+ 'float16', 'longdouble', 'clongdouble',
582
+ 'bool']
583
+ a, q0, r0 = self.generate('tall')
584
+ for dtype in dts:
585
+ q = q0.real.astype(dtype)
586
+ with np.errstate(invalid="ignore"):
587
+ r = r0.real.astype(dtype)
588
+ assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'row')
589
+ assert_raises(ValueError, qr_delete, q, r0, 0, 2, 'row')
590
+ assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'col')
591
+ assert_raises(ValueError, qr_delete, q, r0, 0, 2, 'col')
592
+
593
+ assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'row')
594
+ assert_raises(ValueError, qr_delete, q0, r, 0, 2, 'row')
595
+ assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'col')
596
+ assert_raises(ValueError, qr_delete, q0, r, 0, 2, 'col')
597
+
598
+ def test_check_finite(self):
599
+ a0, q0, r0 = self.generate('tall')
600
+
601
+ q = q0.copy('F')
602
+ q[1,1] = np.nan
603
+ assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'row')
604
+ assert_raises(ValueError, qr_delete, q, r0, 0, 3, 'row')
605
+ assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'col')
606
+ assert_raises(ValueError, qr_delete, q, r0, 0, 3, 'col')
607
+
608
+ r = r0.copy('F')
609
+ r[1,1] = np.nan
610
+ assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'row')
611
+ assert_raises(ValueError, qr_delete, q0, r, 0, 3, 'row')
612
+ assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'col')
613
+ assert_raises(ValueError, qr_delete, q0, r, 0, 3, 'col')
614
+
615
+ def test_qr_scalar(self):
616
+ a, q, r = self.generate('1x1')
617
+ assert_raises(ValueError, qr_delete, q[0, 0], r, 0, 1, 'row')
618
+ assert_raises(ValueError, qr_delete, q, r[0, 0], 0, 1, 'row')
619
+ assert_raises(ValueError, qr_delete, q[0, 0], r, 0, 1, 'col')
620
+ assert_raises(ValueError, qr_delete, q, r[0, 0], 0, 1, 'col')
621
+
622
+ class TestQRdelete_f(BaseQRdelete):
623
+ dtype = np.dtype('f')
624
+
625
+ class TestQRdelete_F(BaseQRdelete):
626
+ dtype = np.dtype('F')
627
+
628
+ class TestQRdelete_d(BaseQRdelete):
629
+ dtype = np.dtype('d')
630
+
631
+ class TestQRdelete_D(BaseQRdelete):
632
+ dtype = np.dtype('D')
633
+
634
+ class BaseQRinsert(BaseQRdeltas):
635
+ def generate(self, type, mode='full', which='row', p=1):
636
+ a, q, r = super().generate(type, mode)
637
+
638
+ assert_(p > 0)
639
+ rng = np.random.default_rng(1234)
640
+
641
+ if which == 'row':
642
+ if p == 1:
643
+ u = rng.random(a.shape[1])
644
+ else:
645
+ u = rng.random((p, a.shape[1]))
646
+ elif which == 'col':
647
+ if p == 1:
648
+ u = rng.random(a.shape[0])
649
+ else:
650
+ u = rng.random((a.shape[0], p))
651
+ else:
652
+ raise ValueError('which should be either "row" or "col"')
653
+
654
+ if np.iscomplexobj(self.dtype.type(1)):
655
+ b = rng.random(u.shape)
656
+ u = u + 1j * b
657
+
658
+ u = u.astype(self.dtype)
659
+ return a, q, r, u
660
+
661
+ def test_sqr_1_row(self):
662
+ a, q, r, u = self.generate('sqr', which='row')
663
+ for row in range(r.shape[0] + 1):
664
+ q1, r1 = qr_insert(q, r, u, row)
665
+ a1 = np.insert(a, row, u, 0)
666
+ check_qr(q1, r1, a1, self.rtol, self.atol)
667
+
668
+ def test_sqr_p_row(self):
669
+ # sqr + rows --> fat always
670
+ a, q, r, u = self.generate('sqr', which='row', p=3)
671
+ for row in range(r.shape[0] + 1):
672
+ q1, r1 = qr_insert(q, r, u, row)
673
+ a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
674
+ check_qr(q1, r1, a1, self.rtol, self.atol)
675
+
676
+ def test_sqr_1_col(self):
677
+ a, q, r, u = self.generate('sqr', which='col')
678
+ for col in range(r.shape[1] + 1):
679
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
680
+ a1 = np.insert(a, col, u, 1)
681
+ check_qr(q1, r1, a1, self.rtol, self.atol)
682
+
683
+ def test_sqr_p_col(self):
684
+ # sqr + cols --> fat always
685
+ a, q, r, u = self.generate('sqr', which='col', p=3)
686
+ for col in range(r.shape[1] + 1):
687
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
688
+ a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
689
+ check_qr(q1, r1, a1, self.rtol, self.atol)
690
+
691
+ def test_tall_1_row(self):
692
+ a, q, r, u = self.generate('tall', which='row')
693
+ for row in range(r.shape[0] + 1):
694
+ q1, r1 = qr_insert(q, r, u, row)
695
+ a1 = np.insert(a, row, u, 0)
696
+ check_qr(q1, r1, a1, self.rtol, self.atol)
697
+
698
+ def test_tall_p_row(self):
699
+ # tall + rows --> tall always
700
+ a, q, r, u = self.generate('tall', which='row', p=3)
701
+ for row in range(r.shape[0] + 1):
702
+ q1, r1 = qr_insert(q, r, u, row)
703
+ a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
704
+ check_qr(q1, r1, a1, self.rtol, self.atol)
705
+
706
+ def test_tall_1_col(self):
707
+ a, q, r, u = self.generate('tall', which='col')
708
+ for col in range(r.shape[1] + 1):
709
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
710
+ a1 = np.insert(a, col, u, 1)
711
+ check_qr(q1, r1, a1, self.rtol, self.atol)
712
+
713
+ # for column adds to tall matrices there are three cases to test
714
+ # tall + pcol --> tall
715
+ # tall + pcol --> sqr
716
+ # tall + pcol --> fat
717
+ def base_tall_p_col_xxx(self, p):
718
+ a, q, r, u = self.generate('tall', which='col', p=p)
719
+ for col in range(r.shape[1] + 1):
720
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
721
+ a1 = np.insert(a, np.full(p, col, np.intp), u, 1)
722
+ check_qr(q1, r1, a1, self.rtol, self.atol)
723
+
724
+ def test_tall_p_col_tall(self):
725
+ # 12x7 + 12x3 = 12x10 --> stays tall
726
+ self.base_tall_p_col_xxx(3)
727
+
728
+ def test_tall_p_col_sqr(self):
729
+ # 12x7 + 12x5 = 12x12 --> becomes sqr
730
+ self.base_tall_p_col_xxx(5)
731
+
732
+ def test_tall_p_col_fat(self):
733
+ # 12x7 + 12x7 = 12x14 --> becomes fat
734
+ self.base_tall_p_col_xxx(7)
735
+
736
+ def test_fat_1_row(self):
737
+ a, q, r, u = self.generate('fat', which='row')
738
+ for row in range(r.shape[0] + 1):
739
+ q1, r1 = qr_insert(q, r, u, row)
740
+ a1 = np.insert(a, row, u, 0)
741
+ check_qr(q1, r1, a1, self.rtol, self.atol)
742
+
743
+ # for row adds to fat matrices there are three cases to test
744
+ # fat + prow --> fat
745
+ # fat + prow --> sqr
746
+ # fat + prow --> tall
747
+ def base_fat_p_row_xxx(self, p):
748
+ a, q, r, u = self.generate('fat', which='row', p=p)
749
+ for row in range(r.shape[0] + 1):
750
+ q1, r1 = qr_insert(q, r, u, row)
751
+ a1 = np.insert(a, np.full(p, row, np.intp), u, 0)
752
+ check_qr(q1, r1, a1, self.rtol, self.atol)
753
+
754
+ def test_fat_p_row_fat(self):
755
+ # 7x12 + 3x12 = 10x12 --> stays fat
756
+ self.base_fat_p_row_xxx(3)
757
+
758
+ def test_fat_p_row_sqr(self):
759
+ # 7x12 + 5x12 = 12x12 --> becomes sqr
760
+ self.base_fat_p_row_xxx(5)
761
+
762
+ def test_fat_p_row_tall(self):
763
+ # 7x12 + 7x12 = 14x12 --> becomes tall
764
+ self.base_fat_p_row_xxx(7)
765
+
766
+ def test_fat_1_col(self):
767
+ a, q, r, u = self.generate('fat', which='col')
768
+ for col in range(r.shape[1] + 1):
769
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
770
+ a1 = np.insert(a, col, u, 1)
771
+ check_qr(q1, r1, a1, self.rtol, self.atol)
772
+
773
+ def test_fat_p_col(self):
774
+ # fat + cols --> fat always
775
+ a, q, r, u = self.generate('fat', which='col', p=3)
776
+ for col in range(r.shape[1] + 1):
777
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
778
+ a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
779
+ check_qr(q1, r1, a1, self.rtol, self.atol)
780
+
781
+ def test_economic_1_row(self):
782
+ a, q, r, u = self.generate('tall', 'economic', 'row')
783
+ for row in range(r.shape[0] + 1):
784
+ q1, r1 = qr_insert(q, r, u, row, overwrite_qru=False)
785
+ a1 = np.insert(a, row, u, 0)
786
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
787
+
788
+ def test_economic_p_row(self):
789
+ # tall + rows --> tall always
790
+ a, q, r, u = self.generate('tall', 'economic', 'row', 3)
791
+ for row in range(r.shape[0] + 1):
792
+ q1, r1 = qr_insert(q, r, u, row, overwrite_qru=False)
793
+ a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
794
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
795
+
796
+ def test_economic_1_col(self):
797
+ a, q, r, u = self.generate('tall', 'economic', which='col')
798
+ for col in range(r.shape[1] + 1):
799
+ q1, r1 = qr_insert(q, r, u.copy(), col, 'col', overwrite_qru=False)
800
+ a1 = np.insert(a, col, u, 1)
801
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
802
+
803
+ def test_economic_1_col_bad_update(self):
804
+ # When the column to be added lies in the span of Q, the update is
805
+ # not meaningful. This is detected, and a LinAlgError is issued.
806
+ q = np.eye(5, 3, dtype=self.dtype)
807
+ r = np.eye(3, dtype=self.dtype)
808
+ u = np.array([1, 0, 0, 0, 0], self.dtype)
809
+ assert_raises(linalg.LinAlgError, qr_insert, q, r, u, 0, 'col')
810
+
811
+ # for column adds to economic matrices there are three cases to test
812
+ # eco + pcol --> eco
813
+ # eco + pcol --> sqr
814
+ # eco + pcol --> fat
815
+ def base_economic_p_col_xxx(self, p):
816
+ a, q, r, u = self.generate('tall', 'economic', which='col', p=p)
817
+ for col in range(r.shape[1] + 1):
818
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
819
+ a1 = np.insert(a, np.full(p, col, np.intp), u, 1)
820
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
821
+
822
+ def test_economic_p_col_eco(self):
823
+ # 12x7 + 12x3 = 12x10 --> stays eco
824
+ self.base_economic_p_col_xxx(3)
825
+
826
+ def test_economic_p_col_sqr(self):
827
+ # 12x7 + 12x5 = 12x12 --> becomes sqr
828
+ self.base_economic_p_col_xxx(5)
829
+
830
+ def test_economic_p_col_fat(self):
831
+ # 12x7 + 12x7 = 12x14 --> becomes fat
832
+ self.base_economic_p_col_xxx(7)
833
+
834
+ def test_Mx1_1_row(self):
835
+ a, q, r, u = self.generate('Mx1', which='row')
836
+ for row in range(r.shape[0] + 1):
837
+ q1, r1 = qr_insert(q, r, u, row)
838
+ a1 = np.insert(a, row, u, 0)
839
+ check_qr(q1, r1, a1, self.rtol, self.atol)
840
+
841
+ def test_Mx1_p_row(self):
842
+ a, q, r, u = self.generate('Mx1', which='row', p=3)
843
+ for row in range(r.shape[0] + 1):
844
+ q1, r1 = qr_insert(q, r, u, row)
845
+ a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
846
+ check_qr(q1, r1, a1, self.rtol, self.atol)
847
+
848
+ def test_Mx1_1_col(self):
849
+ a, q, r, u = self.generate('Mx1', which='col')
850
+ for col in range(r.shape[1] + 1):
851
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
852
+ a1 = np.insert(a, col, u, 1)
853
+ check_qr(q1, r1, a1, self.rtol, self.atol)
854
+
855
+ def test_Mx1_p_col(self):
856
+ a, q, r, u = self.generate('Mx1', which='col', p=3)
857
+ for col in range(r.shape[1] + 1):
858
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
859
+ a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
860
+ check_qr(q1, r1, a1, self.rtol, self.atol)
861
+
862
+ def test_Mx1_economic_1_row(self):
863
+ a, q, r, u = self.generate('Mx1', 'economic', 'row')
864
+ for row in range(r.shape[0] + 1):
865
+ q1, r1 = qr_insert(q, r, u, row)
866
+ a1 = np.insert(a, row, u, 0)
867
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
868
+
869
+ def test_Mx1_economic_p_row(self):
870
+ a, q, r, u = self.generate('Mx1', 'economic', 'row', 3)
871
+ for row in range(r.shape[0] + 1):
872
+ q1, r1 = qr_insert(q, r, u, row)
873
+ a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
874
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
875
+
876
+ def test_Mx1_economic_1_col(self):
877
+ a, q, r, u = self.generate('Mx1', 'economic', 'col')
878
+ for col in range(r.shape[1] + 1):
879
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
880
+ a1 = np.insert(a, col, u, 1)
881
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
882
+
883
+ def test_Mx1_economic_p_col(self):
884
+ a, q, r, u = self.generate('Mx1', 'economic', 'col', 3)
885
+ for col in range(r.shape[1] + 1):
886
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
887
+ a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
888
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
889
+
890
+ def test_1xN_1_row(self):
891
+ a, q, r, u = self.generate('1xN', which='row')
892
+ for row in range(r.shape[0] + 1):
893
+ q1, r1 = qr_insert(q, r, u, row)
894
+ a1 = np.insert(a, row, u, 0)
895
+ check_qr(q1, r1, a1, self.rtol, self.atol)
896
+
897
+ def test_1xN_p_row(self):
898
+ a, q, r, u = self.generate('1xN', which='row', p=3)
899
+ for row in range(r.shape[0] + 1):
900
+ q1, r1 = qr_insert(q, r, u, row)
901
+ a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
902
+ check_qr(q1, r1, a1, self.rtol, self.atol)
903
+
904
+ def test_1xN_1_col(self):
905
+ a, q, r, u = self.generate('1xN', which='col')
906
+ for col in range(r.shape[1] + 1):
907
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
908
+ a1 = np.insert(a, col, u, 1)
909
+ check_qr(q1, r1, a1, self.rtol, self.atol)
910
+
911
+ def test_1xN_p_col(self):
912
+ a, q, r, u = self.generate('1xN', which='col', p=3)
913
+ for col in range(r.shape[1] + 1):
914
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
915
+ a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
916
+ check_qr(q1, r1, a1, self.rtol, self.atol)
917
+
918
+ def test_1x1_1_row(self):
919
+ a, q, r, u = self.generate('1x1', which='row')
920
+ for row in range(r.shape[0] + 1):
921
+ q1, r1 = qr_insert(q, r, u, row)
922
+ a1 = np.insert(a, row, u, 0)
923
+ check_qr(q1, r1, a1, self.rtol, self.atol)
924
+
925
+ def test_1x1_p_row(self):
926
+ a, q, r, u = self.generate('1x1', which='row', p=3)
927
+ for row in range(r.shape[0] + 1):
928
+ q1, r1 = qr_insert(q, r, u, row)
929
+ a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
930
+ check_qr(q1, r1, a1, self.rtol, self.atol)
931
+
932
+ def test_1x1_1_col(self):
933
+ a, q, r, u = self.generate('1x1', which='col')
934
+ for col in range(r.shape[1] + 1):
935
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
936
+ a1 = np.insert(a, col, u, 1)
937
+ check_qr(q1, r1, a1, self.rtol, self.atol)
938
+
939
+ def test_1x1_p_col(self):
940
+ a, q, r, u = self.generate('1x1', which='col', p=3)
941
+ for col in range(r.shape[1] + 1):
942
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
943
+ a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
944
+ check_qr(q1, r1, a1, self.rtol, self.atol)
945
+
946
+ def test_1x1_1_scalar(self):
947
+ a, q, r, u = self.generate('1x1', which='row')
948
+ assert_raises(ValueError, qr_insert, q[0, 0], r, u, 0, 'row')
949
+ assert_raises(ValueError, qr_insert, q, r[0, 0], u, 0, 'row')
950
+ assert_raises(ValueError, qr_insert, q, r, u[0], 0, 'row')
951
+
952
+ assert_raises(ValueError, qr_insert, q[0, 0], r, u, 0, 'col')
953
+ assert_raises(ValueError, qr_insert, q, r[0, 0], u, 0, 'col')
954
+ assert_raises(ValueError, qr_insert, q, r, u[0], 0, 'col')
955
+
956
+ def base_non_simple_strides(self, adjust_strides, k, p, which):
957
+ for type in ['sqr', 'tall', 'fat']:
958
+ a, q0, r0, u0 = self.generate(type, which=which, p=p)
959
+ qs, rs, us = adjust_strides((q0, r0, u0))
960
+ if p == 1:
961
+ ai = np.insert(a, k, u0, 0 if which == 'row' else 1)
962
+ else:
963
+ ai = np.insert(a, np.full(p, k, np.intp),
964
+ u0 if which == 'row' else u0,
965
+ 0 if which == 'row' else 1)
966
+
967
+ # for each variable, q, r, u we try with it strided and
968
+ # overwrite=False. Then we try with overwrite=True. Nothing
969
+ # is checked to see if it can be overwritten, since only
970
+ # F ordered Q can be overwritten when adding columns.
971
+
972
+ q = q0.copy('F')
973
+ r = r0.copy('F')
974
+ u = u0.copy('F')
975
+ q1, r1 = qr_insert(qs, r, u, k, which, overwrite_qru=False)
976
+ check_qr(q1, r1, ai, self.rtol, self.atol)
977
+ q1o, r1o = qr_insert(qs, r, u, k, which, overwrite_qru=True)
978
+ check_qr(q1o, r1o, ai, self.rtol, self.atol)
979
+
980
+ q = q0.copy('F')
981
+ r = r0.copy('F')
982
+ u = u0.copy('F')
983
+ q2, r2 = qr_insert(q, rs, u, k, which, overwrite_qru=False)
984
+ check_qr(q2, r2, ai, self.rtol, self.atol)
985
+ q2o, r2o = qr_insert(q, rs, u, k, which, overwrite_qru=True)
986
+ check_qr(q2o, r2o, ai, self.rtol, self.atol)
987
+
988
+ q = q0.copy('F')
989
+ r = r0.copy('F')
990
+ u = u0.copy('F')
991
+ q3, r3 = qr_insert(q, r, us, k, which, overwrite_qru=False)
992
+ check_qr(q3, r3, ai, self.rtol, self.atol)
993
+ q3o, r3o = qr_insert(q, r, us, k, which, overwrite_qru=True)
994
+ check_qr(q3o, r3o, ai, self.rtol, self.atol)
995
+
996
+ q = q0.copy('F')
997
+ r = r0.copy('F')
998
+ u = u0.copy('F')
999
+ # since some of these were consumed above
1000
+ qs, rs, us = adjust_strides((q, r, u))
1001
+ q5, r5 = qr_insert(qs, rs, us, k, which, overwrite_qru=False)
1002
+ check_qr(q5, r5, ai, self.rtol, self.atol)
1003
+ q5o, r5o = qr_insert(qs, rs, us, k, which, overwrite_qru=True)
1004
+ check_qr(q5o, r5o, ai, self.rtol, self.atol)
1005
+
1006
+ def test_non_unit_strides_1_row(self):
1007
+ self.base_non_simple_strides(make_strided, 0, 1, 'row')
1008
+
1009
+ def test_non_unit_strides_p_row(self):
1010
+ self.base_non_simple_strides(make_strided, 0, 3, 'row')
1011
+
1012
+ def test_non_unit_strides_1_col(self):
1013
+ self.base_non_simple_strides(make_strided, 0, 1, 'col')
1014
+
1015
+ def test_non_unit_strides_p_col(self):
1016
+ self.base_non_simple_strides(make_strided, 0, 3, 'col')
1017
+
1018
+ def test_neg_strides_1_row(self):
1019
+ self.base_non_simple_strides(negate_strides, 0, 1, 'row')
1020
+
1021
+ def test_neg_strides_p_row(self):
1022
+ self.base_non_simple_strides(negate_strides, 0, 3, 'row')
1023
+
1024
+ def test_neg_strides_1_col(self):
1025
+ self.base_non_simple_strides(negate_strides, 0, 1, 'col')
1026
+
1027
+ def test_neg_strides_p_col(self):
1028
+ self.base_non_simple_strides(negate_strides, 0, 3, 'col')
1029
+
1030
+ def test_non_itemsize_strides_1_row(self):
1031
+ self.base_non_simple_strides(nonitemsize_strides, 0, 1, 'row')
1032
+
1033
+ def test_non_itemsize_strides_p_row(self):
1034
+ self.base_non_simple_strides(nonitemsize_strides, 0, 3, 'row')
1035
+
1036
+ def test_non_itemsize_strides_1_col(self):
1037
+ self.base_non_simple_strides(nonitemsize_strides, 0, 1, 'col')
1038
+
1039
+ def test_non_itemsize_strides_p_col(self):
1040
+ self.base_non_simple_strides(nonitemsize_strides, 0, 3, 'col')
1041
+
1042
+ def test_non_native_byte_order_1_row(self):
1043
+ self.base_non_simple_strides(make_nonnative, 0, 1, 'row')
1044
+
1045
+ def test_non_native_byte_order_p_row(self):
1046
+ self.base_non_simple_strides(make_nonnative, 0, 3, 'row')
1047
+
1048
+ def test_non_native_byte_order_1_col(self):
1049
+ self.base_non_simple_strides(make_nonnative, 0, 1, 'col')
1050
+
1051
+ def test_non_native_byte_order_p_col(self):
1052
+ self.base_non_simple_strides(make_nonnative, 0, 3, 'col')
1053
+
1054
+ def test_overwrite_qu_rank_1(self):
1055
+ # when inserting rows, the size of both Q and R change, so only
1056
+ # column inserts can overwrite q. Only complex column inserts
1057
+ # with C ordered Q overwrite u. Any contiguous Q is overwritten
1058
+ # when inserting 1 column
1059
+ a, q0, r, u, = self.generate('sqr', which='col', p=1)
1060
+ q = q0.copy('C')
1061
+ u0 = u.copy()
1062
+ # don't overwrite
1063
+ q1, r1 = qr_insert(q, r, u, 0, 'col', overwrite_qru=False)
1064
+ a1 = np.insert(a, 0, u0, 1)
1065
+ check_qr(q1, r1, a1, self.rtol, self.atol)
1066
+ check_qr(q, r, a, self.rtol, self.atol)
1067
+
1068
+ # try overwriting
1069
+ q2, r2 = qr_insert(q, r, u, 0, 'col', overwrite_qru=True)
1070
+ check_qr(q2, r2, a1, self.rtol, self.atol)
1071
+ # verify the overwriting
1072
+ assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
1073
+ assert_allclose(u, u0.conj(), self.rtol, self.atol)
1074
+
1075
+ # now try with a fortran ordered Q
1076
+ qF = q0.copy('F')
1077
+ u1 = u0.copy()
1078
+ q3, r3 = qr_insert(qF, r, u1, 0, 'col', overwrite_qru=False)
1079
+ check_qr(q3, r3, a1, self.rtol, self.atol)
1080
+ check_qr(qF, r, a, self.rtol, self.atol)
1081
+
1082
+ # try overwriting
1083
+ q4, r4 = qr_insert(qF, r, u1, 0, 'col', overwrite_qru=True)
1084
+ check_qr(q4, r4, a1, self.rtol, self.atol)
1085
+ assert_allclose(q4, qF, rtol=self.rtol, atol=self.atol)
1086
+
1087
+ def test_overwrite_qu_rank_p(self):
1088
+ # when inserting rows, the size of both Q and R change, so only
1089
+ # column inserts can potentially overwrite Q. In practice, only
1090
+ # F ordered Q are overwritten with a rank p update.
1091
+ a, q0, r, u, = self.generate('sqr', which='col', p=3)
1092
+ q = q0.copy('F')
1093
+ a1 = np.insert(a, np.zeros(3, np.intp), u, 1)
1094
+
1095
+ # don't overwrite
1096
+ q1, r1 = qr_insert(q, r, u, 0, 'col', overwrite_qru=False)
1097
+ check_qr(q1, r1, a1, self.rtol, self.atol)
1098
+ check_qr(q, r, a, self.rtol, self.atol)
1099
+
1100
+ # try overwriting
1101
+ q2, r2 = qr_insert(q, r, u, 0, 'col', overwrite_qru=True)
1102
+ check_qr(q2, r2, a1, self.rtol, self.atol)
1103
+ assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
1104
+
1105
+ def test_empty_inputs(self):
1106
+ a, q, r, u = self.generate('sqr', which='row')
1107
+ assert_raises(ValueError, qr_insert, np.array([]), r, u, 0, 'row')
1108
+ assert_raises(ValueError, qr_insert, q, np.array([]), u, 0, 'row')
1109
+ assert_raises(ValueError, qr_insert, q, r, np.array([]), 0, 'row')
1110
+ assert_raises(ValueError, qr_insert, np.array([]), r, u, 0, 'col')
1111
+ assert_raises(ValueError, qr_insert, q, np.array([]), u, 0, 'col')
1112
+ assert_raises(ValueError, qr_insert, q, r, np.array([]), 0, 'col')
1113
+
1114
+ def test_mismatched_shapes(self):
1115
+ a, q, r, u = self.generate('tall', which='row')
1116
+ assert_raises(ValueError, qr_insert, q, r[1:], u, 0, 'row')
1117
+ assert_raises(ValueError, qr_insert, q[:-2], r, u, 0, 'row')
1118
+ assert_raises(ValueError, qr_insert, q, r, u[1:], 0, 'row')
1119
+ assert_raises(ValueError, qr_insert, q, r[1:], u, 0, 'col')
1120
+ assert_raises(ValueError, qr_insert, q[:-2], r, u, 0, 'col')
1121
+ assert_raises(ValueError, qr_insert, q, r, u[1:], 0, 'col')
1122
+
1123
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
1124
+ def test_unsupported_dtypes(self):
1125
+ dts = ['int8', 'int16', 'int32', 'int64',
1126
+ 'uint8', 'uint16', 'uint32', 'uint64',
1127
+ 'float16', 'longdouble', 'clongdouble',
1128
+ 'bool']
1129
+ a, q0, r0, u0 = self.generate('sqr', which='row')
1130
+ for dtype in dts:
1131
+ q = q0.real.astype(dtype)
1132
+ with np.errstate(invalid="ignore"):
1133
+ r = r0.real.astype(dtype)
1134
+ u = u0.real.astype(dtype)
1135
+ assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'row')
1136
+ assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'col')
1137
+ assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'row')
1138
+ assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'col')
1139
+ assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'row')
1140
+ assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'col')
1141
+
1142
+ def test_check_finite(self):
1143
+ a0, q0, r0, u0 = self.generate('sqr', which='row', p=3)
1144
+
1145
+ q = q0.copy('F')
1146
+ q[1,1] = np.nan
1147
+ assert_raises(ValueError, qr_insert, q, r0, u0[:,0], 0, 'row')
1148
+ assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'row')
1149
+ assert_raises(ValueError, qr_insert, q, r0, u0[:,0], 0, 'col')
1150
+ assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'col')
1151
+
1152
+ r = r0.copy('F')
1153
+ r[1,1] = np.nan
1154
+ assert_raises(ValueError, qr_insert, q0, r, u0[:,0], 0, 'row')
1155
+ assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'row')
1156
+ assert_raises(ValueError, qr_insert, q0, r, u0[:,0], 0, 'col')
1157
+ assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'col')
1158
+
1159
+ u = u0.copy('F')
1160
+ u[0,0] = np.nan
1161
+ assert_raises(ValueError, qr_insert, q0, r0, u[:,0], 0, 'row')
1162
+ assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'row')
1163
+ assert_raises(ValueError, qr_insert, q0, r0, u[:,0], 0, 'col')
1164
+ assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'col')
1165
+
1166
+ class TestQRinsert_f(BaseQRinsert):
1167
+ dtype = np.dtype('f')
1168
+
1169
+ class TestQRinsert_F(BaseQRinsert):
1170
+ dtype = np.dtype('F')
1171
+
1172
+ class TestQRinsert_d(BaseQRinsert):
1173
+ dtype = np.dtype('d')
1174
+
1175
+ class TestQRinsert_D(BaseQRinsert):
1176
+ dtype = np.dtype('D')
1177
+
1178
+ class BaseQRupdate(BaseQRdeltas):
1179
+ def generate(self, type, mode='full', p=1):
1180
+ a, q, r = super().generate(type, mode)
1181
+
1182
+ rng = np.random.default_rng(1234)
1183
+ if p == 1:
1184
+ u = rng.random(q.shape[0])
1185
+ v = rng.random(r.shape[1])
1186
+ else:
1187
+ u = rng.random((q.shape[0], p))
1188
+ v = rng.random((r.shape[1], p))
1189
+
1190
+ if np.iscomplexobj(self.dtype.type(1)):
1191
+ b = rng.random(u.shape)
1192
+ u = u + 1j * b
1193
+
1194
+ c = rng.random(v.shape)
1195
+ v = v + 1j * c
1196
+
1197
+ u = u.astype(self.dtype)
1198
+ v = v.astype(self.dtype)
1199
+ return a, q, r, u, v
1200
+
1201
+ def test_sqr_rank_1(self):
1202
+ a, q, r, u, v = self.generate('sqr')
1203
+ q1, r1 = qr_update(q, r, u, v, False)
1204
+ a1 = a + np.outer(u, v.conj())
1205
+ check_qr(q1, r1, a1, self.rtol, self.atol)
1206
+
1207
+ def test_sqr_rank_p(self):
1208
+ # test ndim = 2, rank 1 updates here too
1209
+ for p in [1, 2, 3, 5]:
1210
+ a, q, r, u, v = self.generate('sqr', p=p)
1211
+ if p == 1:
1212
+ u = u.reshape(u.size, 1)
1213
+ v = v.reshape(v.size, 1)
1214
+ q1, r1 = qr_update(q, r, u, v, False)
1215
+ a1 = a + np.dot(u, v.T.conj())
1216
+ check_qr(q1, r1, a1, self.rtol, self.atol)
1217
+
1218
+ def test_tall_rank_1(self):
1219
+ a, q, r, u, v = self.generate('tall')
1220
+ q1, r1 = qr_update(q, r, u, v, False)
1221
+ a1 = a + np.outer(u, v.conj())
1222
+ check_qr(q1, r1, a1, self.rtol, self.atol)
1223
+
1224
+ def test_tall_rank_p(self):
1225
+ for p in [1, 2, 3, 5]:
1226
+ a, q, r, u, v = self.generate('tall', p=p)
1227
+ if p == 1:
1228
+ u = u.reshape(u.size, 1)
1229
+ v = v.reshape(v.size, 1)
1230
+ q1, r1 = qr_update(q, r, u, v, False)
1231
+ a1 = a + np.dot(u, v.T.conj())
1232
+ check_qr(q1, r1, a1, self.rtol, self.atol)
1233
+
1234
+ def test_fat_rank_1(self):
1235
+ a, q, r, u, v = self.generate('fat')
1236
+ q1, r1 = qr_update(q, r, u, v, False)
1237
+ a1 = a + np.outer(u, v.conj())
1238
+ check_qr(q1, r1, a1, self.rtol, self.atol)
1239
+
1240
+ def test_fat_rank_p(self):
1241
+ for p in [1, 2, 3, 5]:
1242
+ a, q, r, u, v = self.generate('fat', p=p)
1243
+ if p == 1:
1244
+ u = u.reshape(u.size, 1)
1245
+ v = v.reshape(v.size, 1)
1246
+ q1, r1 = qr_update(q, r, u, v, False)
1247
+ a1 = a + np.dot(u, v.T.conj())
1248
+ check_qr(q1, r1, a1, self.rtol, self.atol)
1249
+
1250
+ def test_economic_rank_1(self):
1251
+ a, q, r, u, v = self.generate('tall', 'economic')
1252
+ q1, r1 = qr_update(q, r, u, v, False)
1253
+ a1 = a + np.outer(u, v.conj())
1254
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
1255
+
1256
+ def test_economic_rank_p(self):
1257
+ for p in [1, 2, 3, 5]:
1258
+ a, q, r, u, v = self.generate('tall', 'economic', p)
1259
+ if p == 1:
1260
+ u = u.reshape(u.size, 1)
1261
+ v = v.reshape(v.size, 1)
1262
+ q1, r1 = qr_update(q, r, u, v, False)
1263
+ a1 = a + np.dot(u, v.T.conj())
1264
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
1265
+
1266
+ def test_Mx1_rank_1(self):
1267
+ a, q, r, u, v = self.generate('Mx1')
1268
+ q1, r1 = qr_update(q, r, u, v, False)
1269
+ a1 = a + np.outer(u, v.conj())
1270
+ check_qr(q1, r1, a1, self.rtol, self.atol)
1271
+
1272
+ def test_Mx1_rank_p(self):
1273
+ # when M or N == 1, only a rank 1 update is allowed. This isn't
1274
+ # fundamental limitation, but the code does not support it.
1275
+ a, q, r, u, v = self.generate('Mx1', p=1)
1276
+ u = u.reshape(u.size, 1)
1277
+ v = v.reshape(v.size, 1)
1278
+ q1, r1 = qr_update(q, r, u, v, False)
1279
+ a1 = a + np.dot(u, v.T.conj())
1280
+ check_qr(q1, r1, a1, self.rtol, self.atol)
1281
+
1282
+ def test_Mx1_economic_rank_1(self):
1283
+ a, q, r, u, v = self.generate('Mx1', 'economic')
1284
+ q1, r1 = qr_update(q, r, u, v, False)
1285
+ a1 = a + np.outer(u, v.conj())
1286
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
1287
+
1288
+ def test_Mx1_economic_rank_p(self):
1289
+ # when M or N == 1, only a rank 1 update is allowed. This isn't
1290
+ # fundamental limitation, but the code does not support it.
1291
+ a, q, r, u, v = self.generate('Mx1', 'economic', p=1)
1292
+ u = u.reshape(u.size, 1)
1293
+ v = v.reshape(v.size, 1)
1294
+ q1, r1 = qr_update(q, r, u, v, False)
1295
+ a1 = a + np.dot(u, v.T.conj())
1296
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
1297
+
1298
+ def test_1xN_rank_1(self):
1299
+ a, q, r, u, v = self.generate('1xN')
1300
+ q1, r1 = qr_update(q, r, u, v, False)
1301
+ a1 = a + np.outer(u, v.conj())
1302
+ check_qr(q1, r1, a1, self.rtol, self.atol)
1303
+
1304
+ def test_1xN_rank_p(self):
1305
+ # when M or N == 1, only a rank 1 update is allowed. This isn't
1306
+ # fundamental limitation, but the code does not support it.
1307
+ a, q, r, u, v = self.generate('1xN', p=1)
1308
+ u = u.reshape(u.size, 1)
1309
+ v = v.reshape(v.size, 1)
1310
+ q1, r1 = qr_update(q, r, u, v, False)
1311
+ a1 = a + np.dot(u, v.T.conj())
1312
+ check_qr(q1, r1, a1, self.rtol, self.atol)
1313
+
1314
+ def test_1x1_rank_1(self):
1315
+ a, q, r, u, v = self.generate('1x1')
1316
+ q1, r1 = qr_update(q, r, u, v, False)
1317
+ a1 = a + np.outer(u, v.conj())
1318
+ check_qr(q1, r1, a1, self.rtol, self.atol)
1319
+
1320
+ def test_1x1_rank_p(self):
1321
+ # when M or N == 1, only a rank 1 update is allowed. This isn't
1322
+ # fundamental limitation, but the code does not support it.
1323
+ a, q, r, u, v = self.generate('1x1', p=1)
1324
+ u = u.reshape(u.size, 1)
1325
+ v = v.reshape(v.size, 1)
1326
+ q1, r1 = qr_update(q, r, u, v, False)
1327
+ a1 = a + np.dot(u, v.T.conj())
1328
+ check_qr(q1, r1, a1, self.rtol, self.atol)
1329
+
1330
+ def test_1x1_rank_1_scalar(self):
1331
+ a, q, r, u, v = self.generate('1x1')
1332
+ assert_raises(ValueError, qr_update, q[0, 0], r, u, v)
1333
+ assert_raises(ValueError, qr_update, q, r[0, 0], u, v)
1334
+ assert_raises(ValueError, qr_update, q, r, u[0], v)
1335
+ assert_raises(ValueError, qr_update, q, r, u, v[0])
1336
+
1337
+ def base_non_simple_strides(self, adjust_strides, mode, p, overwriteable):
1338
+ assert_sqr = False if mode == 'economic' else True
1339
+ for type in ['sqr', 'tall', 'fat']:
1340
+ a, q0, r0, u0, v0 = self.generate(type, mode, p)
1341
+ qs, rs, us, vs = adjust_strides((q0, r0, u0, v0))
1342
+ if p == 1:
1343
+ aup = a + np.outer(u0, v0.conj())
1344
+ else:
1345
+ aup = a + np.dot(u0, v0.T.conj())
1346
+
1347
+ # for each variable, q, r, u, v we try with it strided and
1348
+ # overwrite=False. Then we try with overwrite=True, and make
1349
+ # sure that if p == 1, r and v are still overwritten.
1350
+ # a strided q and u must always be copied.
1351
+
1352
+ q = q0.copy('F')
1353
+ r = r0.copy('F')
1354
+ u = u0.copy('F')
1355
+ v = v0.copy('C')
1356
+ q1, r1 = qr_update(qs, r, u, v, False)
1357
+ check_qr(q1, r1, aup, self.rtol, self.atol, assert_sqr)
1358
+ q1o, r1o = qr_update(qs, r, u, v, True)
1359
+ check_qr(q1o, r1o, aup, self.rtol, self.atol, assert_sqr)
1360
+ if overwriteable:
1361
+ assert_allclose(r1o, r, rtol=self.rtol, atol=self.atol)
1362
+ assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
1363
+
1364
+ q = q0.copy('F')
1365
+ r = r0.copy('F')
1366
+ u = u0.copy('F')
1367
+ v = v0.copy('C')
1368
+ q2, r2 = qr_update(q, rs, u, v, False)
1369
+ check_qr(q2, r2, aup, self.rtol, self.atol, assert_sqr)
1370
+ q2o, r2o = qr_update(q, rs, u, v, True)
1371
+ check_qr(q2o, r2o, aup, self.rtol, self.atol, assert_sqr)
1372
+ if overwriteable:
1373
+ assert_allclose(r2o, rs, rtol=self.rtol, atol=self.atol)
1374
+ assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
1375
+
1376
+ q = q0.copy('F')
1377
+ r = r0.copy('F')
1378
+ u = u0.copy('F')
1379
+ v = v0.copy('C')
1380
+ q3, r3 = qr_update(q, r, us, v, False)
1381
+ check_qr(q3, r3, aup, self.rtol, self.atol, assert_sqr)
1382
+ q3o, r3o = qr_update(q, r, us, v, True)
1383
+ check_qr(q3o, r3o, aup, self.rtol, self.atol, assert_sqr)
1384
+ if overwriteable:
1385
+ assert_allclose(r3o, r, rtol=self.rtol, atol=self.atol)
1386
+ assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
1387
+
1388
+ q = q0.copy('F')
1389
+ r = r0.copy('F')
1390
+ u = u0.copy('F')
1391
+ v = v0.copy('C')
1392
+ q4, r4 = qr_update(q, r, u, vs, False)
1393
+ check_qr(q4, r4, aup, self.rtol, self.atol, assert_sqr)
1394
+ q4o, r4o = qr_update(q, r, u, vs, True)
1395
+ check_qr(q4o, r4o, aup, self.rtol, self.atol, assert_sqr)
1396
+ if overwriteable:
1397
+ assert_allclose(r4o, r, rtol=self.rtol, atol=self.atol)
1398
+ assert_allclose(vs, v0.conj(), rtol=self.rtol, atol=self.atol)
1399
+
1400
+ q = q0.copy('F')
1401
+ r = r0.copy('F')
1402
+ u = u0.copy('F')
1403
+ v = v0.copy('C')
1404
+ # since some of these were consumed above
1405
+ qs, rs, us, vs = adjust_strides((q, r, u, v))
1406
+ q5, r5 = qr_update(qs, rs, us, vs, False)
1407
+ check_qr(q5, r5, aup, self.rtol, self.atol, assert_sqr)
1408
+ q5o, r5o = qr_update(qs, rs, us, vs, True)
1409
+ check_qr(q5o, r5o, aup, self.rtol, self.atol, assert_sqr)
1410
+ if overwriteable:
1411
+ assert_allclose(r5o, rs, rtol=self.rtol, atol=self.atol)
1412
+ assert_allclose(vs, v0.conj(), rtol=self.rtol, atol=self.atol)
1413
+
1414
+ def test_non_unit_strides_rank_1(self):
1415
+ self.base_non_simple_strides(make_strided, 'full', 1, True)
1416
+
1417
+ def test_non_unit_strides_economic_rank_1(self):
1418
+ self.base_non_simple_strides(make_strided, 'economic', 1, True)
1419
+
1420
+ def test_non_unit_strides_rank_p(self):
1421
+ self.base_non_simple_strides(make_strided, 'full', 3, False)
1422
+
1423
+ def test_non_unit_strides_economic_rank_p(self):
1424
+ self.base_non_simple_strides(make_strided, 'economic', 3, False)
1425
+
1426
+ def test_neg_strides_rank_1(self):
1427
+ self.base_non_simple_strides(negate_strides, 'full', 1, False)
1428
+
1429
+ def test_neg_strides_economic_rank_1(self):
1430
+ self.base_non_simple_strides(negate_strides, 'economic', 1, False)
1431
+
1432
+ def test_neg_strides_rank_p(self):
1433
+ self.base_non_simple_strides(negate_strides, 'full', 3, False)
1434
+
1435
+ def test_neg_strides_economic_rank_p(self):
1436
+ self.base_non_simple_strides(negate_strides, 'economic', 3, False)
1437
+
1438
+ def test_non_itemsize_strides_rank_1(self):
1439
+ self.base_non_simple_strides(nonitemsize_strides, 'full', 1, False)
1440
+
1441
+ def test_non_itemsize_strides_economic_rank_1(self):
1442
+ self.base_non_simple_strides(nonitemsize_strides, 'economic', 1, False)
1443
+
1444
+ def test_non_itemsize_strides_rank_p(self):
1445
+ self.base_non_simple_strides(nonitemsize_strides, 'full', 3, False)
1446
+
1447
+ def test_non_itemsize_strides_economic_rank_p(self):
1448
+ self.base_non_simple_strides(nonitemsize_strides, 'economic', 3, False)
1449
+
1450
+ def test_non_native_byte_order_rank_1(self):
1451
+ self.base_non_simple_strides(make_nonnative, 'full', 1, False)
1452
+
1453
+ def test_non_native_byte_order_economic_rank_1(self):
1454
+ self.base_non_simple_strides(make_nonnative, 'economic', 1, False)
1455
+
1456
+ def test_non_native_byte_order_rank_p(self):
1457
+ self.base_non_simple_strides(make_nonnative, 'full', 3, False)
1458
+
1459
+ def test_non_native_byte_order_economic_rank_p(self):
1460
+ self.base_non_simple_strides(make_nonnative, 'economic', 3, False)
1461
+
1462
+ def test_overwrite_qruv_rank_1(self):
1463
+ # Any positive strided q, r, u, and v can be overwritten for a rank 1
1464
+ # update, only checking C and F contiguous.
1465
+ a, q0, r0, u0, v0 = self.generate('sqr')
1466
+ a1 = a + np.outer(u0, v0.conj())
1467
+ q = q0.copy('F')
1468
+ r = r0.copy('F')
1469
+ u = u0.copy('F')
1470
+ v = v0.copy('F')
1471
+
1472
+ # don't overwrite
1473
+ q1, r1 = qr_update(q, r, u, v, False)
1474
+ check_qr(q1, r1, a1, self.rtol, self.atol)
1475
+ check_qr(q, r, a, self.rtol, self.atol)
1476
+
1477
+ q2, r2 = qr_update(q, r, u, v, True)
1478
+ check_qr(q2, r2, a1, self.rtol, self.atol)
1479
+ # verify the overwriting, no good way to check u and v.
1480
+ assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
1481
+ assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
1482
+
1483
+ q = q0.copy('C')
1484
+ r = r0.copy('C')
1485
+ u = u0.copy('C')
1486
+ v = v0.copy('C')
1487
+ q3, r3 = qr_update(q, r, u, v, True)
1488
+ check_qr(q3, r3, a1, self.rtol, self.atol)
1489
+ assert_allclose(q3, q, rtol=self.rtol, atol=self.atol)
1490
+ assert_allclose(r3, r, rtol=self.rtol, atol=self.atol)
1491
+
1492
+ def test_overwrite_qruv_rank_1_economic(self):
1493
+ # updating economic decompositions can overwrite any contiguous r,
1494
+ # and positively strided r and u. V is only ever read.
1495
+ # only checking C and F contiguous.
1496
+ a, q0, r0, u0, v0 = self.generate('tall', 'economic')
1497
+ a1 = a + np.outer(u0, v0.conj())
1498
+ q = q0.copy('F')
1499
+ r = r0.copy('F')
1500
+ u = u0.copy('F')
1501
+ v = v0.copy('F')
1502
+
1503
+ # don't overwrite
1504
+ q1, r1 = qr_update(q, r, u, v, False)
1505
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
1506
+ check_qr(q, r, a, self.rtol, self.atol, False)
1507
+
1508
+ q2, r2 = qr_update(q, r, u, v, True)
1509
+ check_qr(q2, r2, a1, self.rtol, self.atol, False)
1510
+ # verify the overwriting, no good way to check u and v.
1511
+ assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
1512
+ assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
1513
+
1514
+ q = q0.copy('C')
1515
+ r = r0.copy('C')
1516
+ u = u0.copy('C')
1517
+ v = v0.copy('C')
1518
+ q3, r3 = qr_update(q, r, u, v, True)
1519
+ check_qr(q3, r3, a1, self.rtol, self.atol, False)
1520
+ assert_allclose(q3, q, rtol=self.rtol, atol=self.atol)
1521
+ assert_allclose(r3, r, rtol=self.rtol, atol=self.atol)
1522
+
1523
+ def test_overwrite_qruv_rank_p(self):
1524
+ # for rank p updates, q r must be F contiguous, v must be C (v.T --> F)
1525
+ # and u can be C or F, but is only overwritten if Q is C and complex
1526
+ a, q0, r0, u0, v0 = self.generate('sqr', p=3)
1527
+ a1 = a + np.dot(u0, v0.T.conj())
1528
+ q = q0.copy('F')
1529
+ r = r0.copy('F')
1530
+ u = u0.copy('F')
1531
+ v = v0.copy('C')
1532
+
1533
+ # don't overwrite
1534
+ q1, r1 = qr_update(q, r, u, v, False)
1535
+ check_qr(q1, r1, a1, self.rtol, self.atol)
1536
+ check_qr(q, r, a, self.rtol, self.atol)
1537
+
1538
+ q2, r2 = qr_update(q, r, u, v, True)
1539
+ check_qr(q2, r2, a1, self.rtol, self.atol)
1540
+ # verify the overwriting, no good way to check u and v.
1541
+ assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
1542
+ assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
1543
+
1544
+ def test_empty_inputs(self):
1545
+ a, q, r, u, v = self.generate('tall')
1546
+ assert_raises(ValueError, qr_update, np.array([]), r, u, v)
1547
+ assert_raises(ValueError, qr_update, q, np.array([]), u, v)
1548
+ assert_raises(ValueError, qr_update, q, r, np.array([]), v)
1549
+ assert_raises(ValueError, qr_update, q, r, u, np.array([]))
1550
+
1551
+ def test_mismatched_shapes(self):
1552
+ a, q, r, u, v = self.generate('tall')
1553
+ assert_raises(ValueError, qr_update, q, r[1:], u, v)
1554
+ assert_raises(ValueError, qr_update, q[:-2], r, u, v)
1555
+ assert_raises(ValueError, qr_update, q, r, u[1:], v)
1556
+ assert_raises(ValueError, qr_update, q, r, u, v[1:])
1557
+
1558
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
1559
+ def test_unsupported_dtypes(self):
1560
+ dts = ['int8', 'int16', 'int32', 'int64',
1561
+ 'uint8', 'uint16', 'uint32', 'uint64',
1562
+ 'float16', 'longdouble', 'clongdouble',
1563
+ 'bool']
1564
+ a, q0, r0, u0, v0 = self.generate('tall')
1565
+ for dtype in dts:
1566
+ q = q0.real.astype(dtype)
1567
+ with np.errstate(invalid="ignore"):
1568
+ r = r0.real.astype(dtype)
1569
+ u = u0.real.astype(dtype)
1570
+ v = v0.real.astype(dtype)
1571
+ assert_raises(ValueError, qr_update, q, r0, u0, v0)
1572
+ assert_raises(ValueError, qr_update, q0, r, u0, v0)
1573
+ assert_raises(ValueError, qr_update, q0, r0, u, v0)
1574
+ assert_raises(ValueError, qr_update, q0, r0, u0, v)
1575
+
1576
+ def test_integer_input(self):
1577
+ q = np.arange(16).reshape(4, 4)
1578
+ r = q.copy() # doesn't matter
1579
+ u = q[:, 0].copy()
1580
+ v = r[0, :].copy()
1581
+ assert_raises(ValueError, qr_update, q, r, u, v)
1582
+
1583
+ def test_check_finite(self):
1584
+ a0, q0, r0, u0, v0 = self.generate('tall', p=3)
1585
+
1586
+ q = q0.copy('F')
1587
+ q[1,1] = np.nan
1588
+ assert_raises(ValueError, qr_update, q, r0, u0[:,0], v0[:,0])
1589
+ assert_raises(ValueError, qr_update, q, r0, u0, v0)
1590
+
1591
+ r = r0.copy('F')
1592
+ r[1,1] = np.nan
1593
+ assert_raises(ValueError, qr_update, q0, r, u0[:,0], v0[:,0])
1594
+ assert_raises(ValueError, qr_update, q0, r, u0, v0)
1595
+
1596
+ u = u0.copy('F')
1597
+ u[0,0] = np.nan
1598
+ assert_raises(ValueError, qr_update, q0, r0, u[:,0], v0[:,0])
1599
+ assert_raises(ValueError, qr_update, q0, r0, u, v0)
1600
+
1601
+ v = v0.copy('F')
1602
+ v[0,0] = np.nan
1603
+ assert_raises(ValueError, qr_update, q0, r0, u[:,0], v[:,0])
1604
+ assert_raises(ValueError, qr_update, q0, r0, u, v)
1605
+
1606
+ def test_economic_check_finite(self):
1607
+ a0, q0, r0, u0, v0 = self.generate('tall', mode='economic', p=3)
1608
+
1609
+ q = q0.copy('F')
1610
+ q[1,1] = np.nan
1611
+ assert_raises(ValueError, qr_update, q, r0, u0[:,0], v0[:,0])
1612
+ assert_raises(ValueError, qr_update, q, r0, u0, v0)
1613
+
1614
+ r = r0.copy('F')
1615
+ r[1,1] = np.nan
1616
+ assert_raises(ValueError, qr_update, q0, r, u0[:,0], v0[:,0])
1617
+ assert_raises(ValueError, qr_update, q0, r, u0, v0)
1618
+
1619
+ u = u0.copy('F')
1620
+ u[0,0] = np.nan
1621
+ assert_raises(ValueError, qr_update, q0, r0, u[:,0], v0[:,0])
1622
+ assert_raises(ValueError, qr_update, q0, r0, u, v0)
1623
+
1624
+ v = v0.copy('F')
1625
+ v[0,0] = np.nan
1626
+ assert_raises(ValueError, qr_update, q0, r0, u[:,0], v[:,0])
1627
+ assert_raises(ValueError, qr_update, q0, r0, u, v)
1628
+
1629
+ def test_u_exactly_in_span_q(self):
1630
+ q = np.array([[0, 0], [0, 0], [1, 0], [0, 1]], self.dtype)
1631
+ r = np.array([[1, 0], [0, 1]], self.dtype)
1632
+ u = np.array([0, 0, 0, -1], self.dtype)
1633
+ v = np.array([1, 2], self.dtype)
1634
+ q1, r1 = qr_update(q, r, u, v)
1635
+ a1 = np.dot(q, r) + np.outer(u, v.conj())
1636
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
1637
+
1638
+ class TestQRupdate_f(BaseQRupdate):
1639
+ dtype = np.dtype('f')
1640
+
1641
+ class TestQRupdate_F(BaseQRupdate):
1642
+ dtype = np.dtype('F')
1643
+
1644
+ class TestQRupdate_d(BaseQRupdate):
1645
+ dtype = np.dtype('d')
1646
+
1647
+ class TestQRupdate_D(BaseQRupdate):
1648
+ dtype = np.dtype('D')
1649
+
1650
+ def test_form_qTu():
1651
+ # We want to ensure that all of the code paths through this function are
1652
+ # tested. Most of them should be hit with the rest of test suite, but
1653
+ # explicit tests make clear precisely what is being tested.
1654
+ #
1655
+ # This function expects that Q is either C or F contiguous and square.
1656
+ # Economic mode decompositions (Q is (M, N), M != N) do not go through this
1657
+ # function. U may have any positive strides.
1658
+ #
1659
+ # Some of these test are duplicates, since contiguous 1d arrays are both C
1660
+ # and F.
1661
+
1662
+ q_order = ['F', 'C']
1663
+ q_shape = [(8, 8), ]
1664
+ u_order = ['F', 'C', 'A'] # here A means is not F not C
1665
+ u_shape = [1, 3]
1666
+ dtype = ['f', 'd', 'F', 'D']
1667
+
1668
+ for qo, qs, uo, us, d in \
1669
+ itertools.product(q_order, q_shape, u_order, u_shape, dtype):
1670
+ if us == 1:
1671
+ check_form_qTu(qo, qs, uo, us, 1, d)
1672
+ check_form_qTu(qo, qs, uo, us, 2, d)
1673
+ else:
1674
+ check_form_qTu(qo, qs, uo, us, 2, d)
1675
+
1676
+ def check_form_qTu(q_order, q_shape, u_order, u_shape, u_ndim, dtype):
1677
+ rng = np.random.default_rng(47)
1678
+ if u_shape == 1 and u_ndim == 1:
1679
+ u_shape = (q_shape[0],)
1680
+ else:
1681
+ u_shape = (q_shape[0], u_shape)
1682
+ dtype = np.dtype(dtype)
1683
+
1684
+ if dtype.char in 'fd':
1685
+ q = rng.random(q_shape)
1686
+ u = rng.random(u_shape)
1687
+ elif dtype.char in 'FD':
1688
+ q = rng.random(q_shape) + 1j*rng.random(q_shape)
1689
+ u = rng.random(u_shape) + 1j*rng.random(u_shape)
1690
+ else:
1691
+ raise ValueError("form_qTu doesn't support this dtype")
1692
+
1693
+ q = np.require(q, dtype, q_order)
1694
+ if u_order != 'A':
1695
+ u = np.require(u, dtype, u_order)
1696
+ else:
1697
+ u, = make_strided((u.astype(dtype),))
1698
+
1699
+ rtol = 10.0 ** -(np.finfo(dtype).precision-2)
1700
+ atol = 2*np.finfo(dtype).eps
1701
+
1702
+ expected = np.dot(q.T.conj(), u)
1703
+ res = _decomp_update._form_qTu(q, u)
1704
+ assert_allclose(res, expected, rtol=rtol, atol=atol)
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_deprecations.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''Test dtype deprecations.
2
+ '''
3
+ import numpy as np
4
+ import scipy.linalg as linalg
5
+ import pytest
6
+
7
+ from scipy._lib._array_api import SCIPY_ARRAY_API
8
+
9
+ #
10
+ # When the deprecation expires
11
+ # 1. Change the test from asserting a DeprecationWarning to assert_raises
12
+ # 2. Remove the `_skip_dict` dictionary: it is only used to tell things which
13
+ # already raise errors from things which now emit DeprecationWarnings
14
+
15
+
16
+ # skip these completely
17
+ _skip_names = [
18
+ # not functions
19
+ 'LinAlgError', 'LinAlgWarning',
20
+ # do not touch the low-level `scipy.linalg.{blas,lapack}`
21
+ 'get_lapack_funcs', 'get_blas_funcs', 'find_best_blas_type',
22
+ # qr_update skip for now
23
+ 'qr_update', 'qr_insert', 'qr_delete',
24
+ # special matrix constructors do not use LAPACK
25
+ 'block_diag',
26
+ 'toeplitz', 'circulant', 'hankel', 'hadamard', 'leslie', 'companion',
27
+ 'helmert', 'hilbert', 'invhilbert', 'pascal', 'invpascal', 'dft',
28
+ 'fiedler', 'fiedler_companion', 'convolution_matrix',
29
+ # _sketches does not use LAPACK
30
+ 'clarkson_woodruff_transform',
31
+ # these did not accepted weird dtypes already
32
+ 'expm', 'tanm', 'tanhm', 'sinm', 'cosm', 'sinhm', 'coshm', 'expm_cond',
33
+ 'solve_continuous_are',
34
+ 'rsf2csf',
35
+ ]
36
+
37
+
38
+ # use this for dtype-specific skips
39
+ # (e.g. if something only accepts real arrays, add complex typecodes here.)
40
+ _skip_dict = {
41
+ # TypeError: Only real arrays currently supported
42
+ 'eigh_tridiagonal': 'G',
43
+ 'eigvalsh_tridiagonal': 'G',
44
+ # TypeError: No matching signature found
45
+ 'issymmetric': 'eGmM',
46
+ 'ishermitian': 'eGmM',
47
+ 'bandwidth': 'egGmM',
48
+ # already raise
49
+ 'det': 'gGmM',
50
+ 'expm': 'gG',
51
+
52
+ # datetime specific + float16 specific
53
+ 'cdf2rdf' : 'mM',
54
+ 'expm_frechet' : 'mM' + 'e',
55
+ 'pinv': 'mM',
56
+ 'signm': 'mM',
57
+ 'fractional_matrix_power' : 'mM' + 'e',
58
+ 'khatri_rao' : 'mM',
59
+ 'logm' : 'mM' + 'e',
60
+ 'orthogonal_procrustes' : 'mM' + 'e',
61
+ 'solve_circulant' : 'mM',
62
+ 'solve_continuous_lyapunov': 'M',
63
+ 'solve_discrete_lyapunov': 'mM' + 'e',
64
+ 'solve_lyapunov' : 'M',
65
+ 'solve_sylvester' : 'mM',
66
+ 'solve_discrete_are': 'mM',
67
+ 'matmul_toeplitz': 'mM',
68
+ 'solve_toeplitz': 'mM',
69
+ }
70
+
71
+
72
+ # these raise if SCIPY_ARRAY_API env var is defined
73
+ _array_api_skip_dict = {
74
+ 'cho_factor' : 'mM',
75
+ 'cho_solve' : 'mM',
76
+ 'cho_solve_banded' : 'mM',
77
+ 'cholesky' : 'mM',
78
+ 'cholesky_banded' : 'mM',
79
+ 'cossin' : 'mM',
80
+ 'diagsvd' : 'mM',
81
+ 'eig_banded' : 'mM',
82
+ 'eigh' : 'mM',
83
+ 'eigh_tridiagonal' : 'mM',
84
+ 'eigvals_banded' : 'mM',
85
+ 'eigvalsh' : 'mM',
86
+ 'eigvalsh_tridiagonal' : 'mM',
87
+ 'funm' : 'mM',
88
+ 'hessenberg' : 'mM',
89
+ 'ldl' : 'mM',
90
+ 'lu_factor' : 'mM',
91
+ 'lu_solve' : 'mM',
92
+ 'matrix_balance' : 'mM',
93
+ 'null_space' : 'mM',
94
+ 'ordqz' : 'mM',
95
+ 'orth' : 'mM',
96
+ 'pinvh' : 'mM',
97
+ 'polar' : 'mM',
98
+ 'qr' : 'mM',
99
+ 'qr_multiply' : 'mM',
100
+ 'qz' : 'mM',
101
+ 'rq' : 'mM',
102
+ 'schur' : 'mM',
103
+ 'solve_banded' : 'mM',
104
+ 'solve_continuous_lyapunov' : 'mM',
105
+ 'solve_lyapunov' : 'mM',
106
+ 'solve_triangular' : 'mM',
107
+ 'solveh_banded' : 'mM',
108
+ 'subspace_angles' : 'mM',
109
+ }
110
+
111
+
112
+ if SCIPY_ARRAY_API:
113
+ #_skip_dict.update(**_array_api_skip_dict)
114
+ for key, val in _array_api_skip_dict.items():
115
+ if key in _skip_dict:
116
+ _skip_dict[key] += val
117
+ else:
118
+ _skip_dict[key] = val
119
+
120
+
121
+ # loop over all names
122
+ _names = linalg.__all__
123
+ _objs = {name: getattr(linalg, name)
124
+ for name in _names
125
+ if name not in _skip_names
126
+ }
127
+ _objs = {name: obj for name,obj in _objs.items() if callable(obj)}
128
+
129
+
130
+ # Some gymnastics to prepare a set of arguments which all functions can accept
131
+ _two_arg_names = set([
132
+ 'cdf2rdf', 'rsf2csf', 'solve', 'solve_triangular', 'lstsq', 'khatri_rao',
133
+ 'subspace_angles', 'qz', 'ordqz', 'orthogonal_procrustes', 'solve_circulant',
134
+ 'solve_discrete_lyapunov', 'solve_continuous_lyapunov', 'solve_lyapunov',
135
+ 'expm_frechet',
136
+ 'matmul_toeplitz', 'solve_toeplitz', 'lu_solve',
137
+ 'eigh_tridiagonal', 'eigvalsh_tridiagonal',
138
+ 'solveh_banded', 'solve_banded', 'solveh_banded', 'qr_multiply',
139
+ ])
140
+
141
+ _three_arg_names = set(['solve_sylvester'])
142
+
143
+ _four_arg_names = set(['solve_continuous_are', 'solve_discrete_are'])
144
+
145
+ _arr_and_int_names = set([
146
+ 'clarkson_woodruff_transform', 'convolution_matrix', 'fractional_matrix_power',
147
+ ])
148
+
149
+ _arr_and_two_int_names = set(['diagsvd', 'cossin'])
150
+
151
+
152
+ def _patch_args(func_name, args):
153
+ '''Make sure func(*args) does not raise because *args is wrong.'''
154
+ if func_name == 'cdf2rdf':
155
+ args = (args[0][0], args[1]) # cdf2rd(1d, 2d)
156
+ elif func_name == 'funm':
157
+ args = (args[0], lambda x: x)
158
+ elif func_name == 'lu_solve':
159
+ a = args[0]
160
+ piv = np.arange(a.shape[0])
161
+ args = ((a, piv), args[1])
162
+ elif func_name in ('eigh_tridiagonal', 'eigvalsh_tridiagonal'):
163
+ d, e = args
164
+ args = (d, e[:, :-1])
165
+ elif func_name == 'cossin':
166
+ a = args[0]
167
+ args = (a, a.shape[0]//2, a.shape[1]//2)
168
+ elif func_name == 'solve_banded':
169
+ from scipy.linalg._basic import _to_banded
170
+ args = ((1, 2), _to_banded(1, 2, args[0]), args[0])
171
+ elif func_name == 'solveh_banded':
172
+ from scipy.linalg._basic import _to_banded
173
+ args = (_to_banded(0, 2, args[0])[:, :-1], args[0][0, :-1])
174
+ elif func_name == 'cholesky_banded':
175
+ from scipy.linalg._basic import _to_banded
176
+ args = (_to_banded(0, 2, args[0])[:, :-1],)
177
+ elif func_name == 'solve_toeplitz':
178
+ c = args[0][1]
179
+ args = (c, np.ones_like(c))
180
+ return args
181
+
182
+
183
+ @pytest.mark.skip_xp_backends(np_only=True)
184
+ @pytest.mark.filterwarnings(
185
+ 'ignore:attempting to conjugate non-numeric dtype:DeprecationWarning'
186
+ )
187
+ @pytest.mark.filterwarnings('ignore:overflow encountered in dot:RuntimeWarning')
188
+ @pytest.mark.filterwarnings('ignore:invalid value encountered in dot:RuntimeWarning')
189
+ @pytest.mark.filterwarnings('ignore:logm result may be inaccurate:RuntimeWarning')
190
+ @pytest.mark.filterwarnings('ignore:overflow encountered in multiply:RuntimeWarning')
191
+ @pytest.mark.parametrize('func_name', _objs.keys())
192
+ @pytest.mark.parametrize('tcode', 'e' + 'mMgG')
193
+ def test_deprecations(func_name, tcode):
194
+ func = _objs[func_name]
195
+
196
+ if tcode in _skip_dict.get(func_name, ''):
197
+ return
198
+
199
+ a = np.arange(16).reshape(4, 4) + 8*np.eye(4)
200
+ a = a.T @ a
201
+ a = a.astype(tcode)
202
+
203
+ if func_name in _two_arg_names:
204
+ b = a.copy()
205
+ args = (a, b)
206
+ elif func_name in _three_arg_names:
207
+ args = (a, a, a)
208
+ elif func_name in _four_arg_names:
209
+ args = (a, a, a, a)
210
+ elif func_name in _arr_and_int_names:
211
+ args = (a, a.shape[0])
212
+ elif func_name in _arr_and_two_int_names:
213
+ args = (a, a.shape[0], a.shape[1])
214
+ elif func_name in ['cho_solve', 'cho_solve_banded']:
215
+ args = ((a, True), a)
216
+ else:
217
+ args = (a,)
218
+
219
+ args = _patch_args(func_name, args)
220
+
221
+ with pytest.warns(DeprecationWarning):
222
+ func(*args)
223
+
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_extending.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import platform
3
+ import sysconfig
4
+
5
+ import numpy as np
6
+ import pytest
7
+
8
+ from scipy._lib._testutils import IS_EDITABLE, _test_cython_extension, cython
9
+ from scipy.linalg.blas import get_blas_funcs
10
+ from scipy.linalg.lapack import get_lapack_funcs
11
+ import scipy.linalg.cython_blas as cython_blas
12
+
13
+
14
+ @pytest.mark.parallel_threads_limit(4) # 0.35 GiB per thread RAM usage
15
+ @pytest.mark.fail_slow(120)
16
+ # essential per https://github.com/scipy/scipy/pull/20487#discussion_r1567057247
17
+ @pytest.mark.skipif(IS_EDITABLE,
18
+ reason='Editable install cannot find .pxd headers.')
19
+ @pytest.mark.skipif((platform.system() == 'Windows' and
20
+ sysconfig.get_config_var('Py_GIL_DISABLED')),
21
+ reason='gh-22039')
22
+ @pytest.mark.skipif(platform.machine() in ["wasm32", "wasm64"],
23
+ reason="Can't start subprocess")
24
+ @pytest.mark.skipif(cython is None, reason="requires cython")
25
+ def test_cython(tmp_path):
26
+ srcdir = os.path.dirname(os.path.dirname(__file__))
27
+ extensions, extensions_cpp = _test_cython_extension(tmp_path, srcdir)
28
+ # actually test the cython c-extensions
29
+ a = np.ones(8) * 3
30
+ b = np.ones(9)
31
+ c = np.ones(8) * 4
32
+ x = np.ones(9)
33
+ dgtsv = get_lapack_funcs('gtsv', dtype=np.float64, ilp64="preferred")
34
+ _, _, _, x, _ = dgtsv(a, b, c, x)
35
+ a = np.ones(8) * 3
36
+ b = np.ones(9)
37
+ c = np.ones(8) * 4
38
+ x_c = np.ones(9)
39
+ extensions.tridiag(a, b, c, x_c)
40
+ a = np.ones(8) * 3
41
+ b = np.ones(9)
42
+ c = np.ones(8) * 4
43
+ x_cpp = np.ones(9)
44
+ extensions_cpp.tridiag(a, b, c, x_cpp)
45
+ np.testing.assert_array_equal(x, x_cpp)
46
+ cx = np.array([1-1j, 2+2j, 3-3j], dtype=np.complex64)
47
+ cy = np.array([4+4j, 5-5j, 6+6j], dtype=np.complex64)
48
+ cdotu = get_blas_funcs('dotu', dtype=np.complex64, ilp64="preferred")
49
+ np.testing.assert_array_equal(cdotu(cx, cy), extensions.complex_dot(cx, cy))
50
+ np.testing.assert_array_equal(cdotu(cx, cy), extensions_cpp.complex_dot(cx, cy))
51
+
52
+ # Verify blas_int size consistency between installed and JIT-compiled modules
53
+ expected_size = cython_blas._blas_int_size()
54
+ assert extensions.get_blas_int_size() == expected_size
55
+ assert extensions_cpp.get_blas_int_size() == expected_size
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_fblas.py ADDED
@@ -0,0 +1,610 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Test interfaces to fortran blas.
2
+ #
3
+ # The tests are more of interface than they are of the underlying blas.
4
+ # Only very small matrices checked -- N=3 or so.
5
+ #
6
+ # !! Complex calculations really aren't checked that carefully.
7
+ # !! Only real valued complex numbers are used in tests.
8
+ from itertools import product
9
+ import sys
10
+
11
+ import numpy as np
12
+ import pytest
13
+ from numpy import float32, float64, complex64, complex128, arange, array, \
14
+ zeros, shape, transpose, newaxis, common_type, conjugate
15
+
16
+ from numpy.testing import (
17
+ assert_array_equal, assert_allclose, assert_array_almost_equal, assert_
18
+ )
19
+
20
+ import scipy
21
+
22
+ blas_config = scipy.show_config(mode='dicts')['Build Dependencies']['blas']
23
+ if blas_config['cython blas ilp64']:
24
+ pytestmark = pytest.skip(allow_module_level=True,
25
+ reason="LP64 _fblas wasn't built")
26
+
27
+ from scipy.linalg import _fblas as fblas # noqa: E402
28
+
29
+
30
+ # decimal accuracy to require between Python and LAPACK/BLAS calculations
31
+ accuracy = 5
32
+
33
+ # Since numpy.dot likely uses the same blas, use this routine
34
+ # to check.
35
+
36
+
37
+ def matrixmultiply(a, b):
38
+ if len(b.shape) == 1:
39
+ b_is_vector = True
40
+ b = b[:, newaxis]
41
+ else:
42
+ b_is_vector = False
43
+ assert_(a.shape[1] == b.shape[0])
44
+ c = zeros((a.shape[0], b.shape[1]), common_type(a, b))
45
+ for i in range(a.shape[0]):
46
+ for j in range(b.shape[1]):
47
+ s = 0
48
+ for k in range(a.shape[1]):
49
+ s += a[i, k] * b[k, j]
50
+ c[i, j] = s
51
+ if b_is_vector:
52
+ c = c.reshape((a.shape[0],))
53
+ return c
54
+
55
+ ##################################################
56
+ # Test blas ?axpy
57
+
58
+
59
+ class BaseAxpy:
60
+ ''' Mixin class for axpy tests '''
61
+
62
+ def test_default_a(self):
63
+ x = arange(3., dtype=self.dtype)
64
+ y = arange(3., dtype=x.dtype)
65
+ real_y = x*1.+y
66
+ y = self.blas_func(x, y)
67
+ assert_array_equal(real_y, y)
68
+
69
+ def test_simple(self):
70
+ x = arange(3., dtype=self.dtype)
71
+ y = arange(3., dtype=x.dtype)
72
+ real_y = x*3.+y
73
+ y = self.blas_func(x, y, a=3.)
74
+ assert_array_equal(real_y, y)
75
+
76
+ def test_x_stride(self):
77
+ x = arange(6., dtype=self.dtype)
78
+ y = zeros(3, x.dtype)
79
+ y = arange(3., dtype=x.dtype)
80
+ real_y = x[::2]*3.+y
81
+ y = self.blas_func(x, y, a=3., n=3, incx=2)
82
+ assert_array_equal(real_y, y)
83
+
84
+ def test_y_stride(self):
85
+ x = arange(3., dtype=self.dtype)
86
+ y = zeros(6, x.dtype)
87
+ real_y = x*3.+y[::2]
88
+ y = self.blas_func(x, y, a=3., n=3, incy=2)
89
+ assert_array_equal(real_y, y[::2])
90
+
91
+ def test_x_and_y_stride(self):
92
+ x = arange(12., dtype=self.dtype)
93
+ y = zeros(6, x.dtype)
94
+ real_y = x[::4]*3.+y[::2]
95
+ y = self.blas_func(x, y, a=3., n=3, incx=4, incy=2)
96
+ assert_array_equal(real_y, y[::2])
97
+
98
+ def test_x_bad_size(self):
99
+ x = arange(12., dtype=self.dtype)
100
+ y = zeros(6, x.dtype)
101
+ with pytest.raises(Exception, match='failed for 1st keyword'):
102
+ self.blas_func(x, y, n=4, incx=5)
103
+
104
+ def test_y_bad_size(self):
105
+ x = arange(12., dtype=self.dtype)
106
+ y = zeros(6, x.dtype)
107
+ with pytest.raises(Exception, match='failed for 1st keyword'):
108
+ self.blas_func(x, y, n=3, incy=5)
109
+
110
+
111
+ try:
112
+ class TestSaxpy(BaseAxpy):
113
+ blas_func = fblas.saxpy
114
+ dtype = float32
115
+ except AttributeError:
116
+ class TestSaxpy:
117
+ pass
118
+
119
+
120
+ class TestDaxpy(BaseAxpy):
121
+ blas_func = fblas.daxpy
122
+ dtype = float64
123
+
124
+
125
+ try:
126
+ class TestCaxpy(BaseAxpy):
127
+ blas_func = fblas.caxpy
128
+ dtype = complex64
129
+ except AttributeError:
130
+ class TestCaxpy:
131
+ pass
132
+
133
+
134
+ class TestZaxpy(BaseAxpy):
135
+ blas_func = fblas.zaxpy
136
+ dtype = complex128
137
+
138
+
139
+ ##################################################
140
+ # Test blas ?scal
141
+
142
+ class BaseScal:
143
+ ''' Mixin class for scal testing '''
144
+
145
+ def test_simple(self):
146
+ x = arange(3., dtype=self.dtype)
147
+ real_x = x*3.
148
+ x = self.blas_func(3., x)
149
+ assert_array_equal(real_x, x)
150
+
151
+ def test_x_stride(self):
152
+ x = arange(6., dtype=self.dtype)
153
+ real_x = x.copy()
154
+ real_x[::2] = x[::2]*array(3., self.dtype)
155
+ x = self.blas_func(3., x, n=3, incx=2)
156
+ assert_array_equal(real_x, x)
157
+
158
+ def test_x_bad_size(self):
159
+ x = arange(12., dtype=self.dtype)
160
+ with pytest.raises(Exception, match='failed for 1st keyword'):
161
+ self.blas_func(2., x, n=4, incx=5)
162
+
163
+
164
+ try:
165
+ class TestSscal(BaseScal):
166
+ blas_func = fblas.sscal
167
+ dtype = float32
168
+ except AttributeError:
169
+ class TestSscal:
170
+ pass
171
+
172
+
173
+ class TestDscal(BaseScal):
174
+ blas_func = fblas.dscal
175
+ dtype = float64
176
+
177
+
178
+ try:
179
+ class TestCscal(BaseScal):
180
+ blas_func = fblas.cscal
181
+ dtype = complex64
182
+ except AttributeError:
183
+ class TestCscal:
184
+ pass
185
+
186
+
187
+ class TestZscal(BaseScal):
188
+ blas_func = fblas.zscal
189
+ dtype = complex128
190
+
191
+
192
+ ##################################################
193
+ # Test blas ?copy
194
+
195
+ class BaseCopy:
196
+ ''' Mixin class for copy testing '''
197
+
198
+ def test_simple(self):
199
+ x = arange(3., dtype=self.dtype)
200
+ y = zeros(shape(x), x.dtype)
201
+ y = self.blas_func(x, y)
202
+ assert_array_equal(x, y)
203
+
204
+ def test_x_stride(self):
205
+ x = arange(6., dtype=self.dtype)
206
+ y = zeros(3, x.dtype)
207
+ y = self.blas_func(x, y, n=3, incx=2)
208
+ assert_array_equal(x[::2], y)
209
+
210
+ def test_y_stride(self):
211
+ x = arange(3., dtype=self.dtype)
212
+ y = zeros(6, x.dtype)
213
+ y = self.blas_func(x, y, n=3, incy=2)
214
+ assert_array_equal(x, y[::2])
215
+
216
+ def test_x_and_y_stride(self):
217
+ x = arange(12., dtype=self.dtype)
218
+ y = zeros(6, x.dtype)
219
+ y = self.blas_func(x, y, n=3, incx=4, incy=2)
220
+ assert_array_equal(x[::4], y[::2])
221
+
222
+ def test_x_bad_size(self):
223
+ x = arange(12., dtype=self.dtype)
224
+ y = zeros(6, x.dtype)
225
+ with pytest.raises(Exception, match='failed for 1st keyword'):
226
+ self.blas_func(x, y, n=4, incx=5)
227
+
228
+ def test_y_bad_size(self):
229
+ x = arange(12., dtype=self.dtype)
230
+ y = zeros(6, x.dtype)
231
+ with pytest.raises(Exception, match='failed for 1st keyword'):
232
+ self.blas_func(x, y, n=3, incy=5)
233
+
234
+ # def test_y_bad_type(self):
235
+ ## Hmmm. Should this work? What should be the output.
236
+ # x = arange(3.,dtype=self.dtype)
237
+ # y = zeros(shape(x))
238
+ # self.blas_func(x,y)
239
+ # assert_array_equal(x,y)
240
+
241
+
242
+ try:
243
+ class TestScopy(BaseCopy):
244
+ blas_func = fblas.scopy
245
+ dtype = float32
246
+ except AttributeError:
247
+ class TestScopy:
248
+ pass
249
+
250
+
251
+ class TestDcopy(BaseCopy):
252
+ blas_func = fblas.dcopy
253
+ dtype = float64
254
+
255
+
256
+ try:
257
+ class TestCcopy(BaseCopy):
258
+ blas_func = fblas.ccopy
259
+ dtype = complex64
260
+ except AttributeError:
261
+ class TestCcopy:
262
+ pass
263
+
264
+
265
+ class TestZcopy(BaseCopy):
266
+ blas_func = fblas.zcopy
267
+ dtype = complex128
268
+
269
+
270
+ ##################################################
271
+ # Test blas ?swap
272
+
273
+ class BaseSwap:
274
+ ''' Mixin class for swap tests '''
275
+
276
+ def test_simple(self):
277
+ x = arange(3., dtype=self.dtype)
278
+ y = zeros(shape(x), x.dtype)
279
+ desired_x = y.copy()
280
+ desired_y = x.copy()
281
+ x, y = self.blas_func(x, y)
282
+ assert_array_equal(desired_x, x)
283
+ assert_array_equal(desired_y, y)
284
+
285
+ def test_x_stride(self):
286
+ x = arange(6., dtype=self.dtype)
287
+ y = zeros(3, x.dtype)
288
+ desired_x = y.copy()
289
+ desired_y = x.copy()[::2]
290
+ x, y = self.blas_func(x, y, n=3, incx=2)
291
+ assert_array_equal(desired_x, x[::2])
292
+ assert_array_equal(desired_y, y)
293
+
294
+ def test_y_stride(self):
295
+ x = arange(3., dtype=self.dtype)
296
+ y = zeros(6, x.dtype)
297
+ desired_x = y.copy()[::2]
298
+ desired_y = x.copy()
299
+ x, y = self.blas_func(x, y, n=3, incy=2)
300
+ assert_array_equal(desired_x, x)
301
+ assert_array_equal(desired_y, y[::2])
302
+
303
+ def test_x_and_y_stride(self):
304
+ x = arange(12., dtype=self.dtype)
305
+ y = zeros(6, x.dtype)
306
+ desired_x = y.copy()[::2]
307
+ desired_y = x.copy()[::4]
308
+ x, y = self.blas_func(x, y, n=3, incx=4, incy=2)
309
+ assert_array_equal(desired_x, x[::4])
310
+ assert_array_equal(desired_y, y[::2])
311
+
312
+ def test_x_bad_size(self):
313
+ x = arange(12., dtype=self.dtype)
314
+ y = zeros(6, x.dtype)
315
+ with pytest.raises(Exception, match='failed for 1st keyword'):
316
+ self.blas_func(x, y, n=4, incx=5)
317
+
318
+ def test_y_bad_size(self):
319
+ x = arange(12., dtype=self.dtype)
320
+ y = zeros(6, x.dtype)
321
+ with pytest.raises(Exception, match='failed for 1st keyword'):
322
+ self.blas_func(x, y, n=3, incy=5)
323
+
324
+
325
+ try:
326
+ class TestSswap(BaseSwap):
327
+ blas_func = fblas.sswap
328
+ dtype = float32
329
+ except AttributeError:
330
+ class TestSswap:
331
+ pass
332
+
333
+
334
+ class TestDswap(BaseSwap):
335
+ blas_func = fblas.dswap
336
+ dtype = float64
337
+
338
+
339
+ try:
340
+ class TestCswap(BaseSwap):
341
+ blas_func = fblas.cswap
342
+ dtype = complex64
343
+ except AttributeError:
344
+ class TestCswap:
345
+ pass
346
+
347
+
348
+ class TestZswap(BaseSwap):
349
+ blas_func = fblas.zswap
350
+ dtype = complex128
351
+
352
+ ##################################################
353
+ # Test blas ?gemv
354
+ # This will be a mess to test all cases.
355
+
356
+
357
+ class BaseGemv:
358
+ ''' Mixin class for gemv tests '''
359
+
360
+ def get_data(self, x_stride=1, y_stride=1):
361
+ rng = np.random.default_rng(1234)
362
+ mult = array(1, dtype=self.dtype)
363
+ if self.dtype in [complex64, complex128]:
364
+ mult = array(1+1j, dtype=self.dtype)
365
+ alpha = array(1., dtype=self.dtype) * mult
366
+ beta = array(1., dtype=self.dtype) * mult
367
+ a = rng.normal(0., 1., (3, 3)).astype(self.dtype) * mult
368
+ x = arange(shape(a)[0]*x_stride, dtype=self.dtype) * mult
369
+ y = arange(shape(a)[1]*y_stride, dtype=self.dtype) * mult
370
+ return alpha, beta, a, x, y
371
+
372
+ def test_simple(self):
373
+ alpha, beta, a, x, y = self.get_data()
374
+ desired_y = alpha*matrixmultiply(a, x)+beta*y
375
+ y = self.blas_func(alpha, a, x, beta, y)
376
+ assert_array_almost_equal(desired_y, y)
377
+
378
+ def test_default_beta_y(self):
379
+ alpha, beta, a, x, y = self.get_data()
380
+ desired_y = matrixmultiply(a, x)
381
+ y = self.blas_func(1, a, x)
382
+ assert_array_almost_equal(desired_y, y)
383
+
384
+ def test_simple_transpose(self):
385
+ alpha, beta, a, x, y = self.get_data()
386
+ desired_y = alpha*matrixmultiply(transpose(a), x)+beta*y
387
+ y = self.blas_func(alpha, a, x, beta, y, trans=1)
388
+ assert_array_almost_equal(desired_y, y)
389
+
390
+ def test_simple_transpose_conj(self):
391
+ alpha, beta, a, x, y = self.get_data()
392
+ desired_y = alpha*matrixmultiply(transpose(conjugate(a)), x)+beta*y
393
+ y = self.blas_func(alpha, a, x, beta, y, trans=2)
394
+ assert_array_almost_equal(desired_y, y)
395
+
396
+ def test_x_stride(self):
397
+ alpha, beta, a, x, y = self.get_data(x_stride=2)
398
+ desired_y = alpha*matrixmultiply(a, x[::2])+beta*y
399
+ y = self.blas_func(alpha, a, x, beta, y, incx=2)
400
+ assert_array_almost_equal(desired_y, y)
401
+
402
+ def test_x_stride_transpose(self):
403
+ alpha, beta, a, x, y = self.get_data(x_stride=2)
404
+ desired_y = alpha*matrixmultiply(transpose(a), x[::2])+beta*y
405
+ y = self.blas_func(alpha, a, x, beta, y, trans=1, incx=2)
406
+ assert_array_almost_equal(desired_y, y)
407
+
408
+ def test_x_stride_assert(self):
409
+ # What is the use of this test?
410
+ alpha, beta, a, x, y = self.get_data(x_stride=2)
411
+ with pytest.raises(Exception, match='failed for 3rd argument'):
412
+ y = self.blas_func(1, a, x, 1, y, trans=0, incx=3)
413
+ with pytest.raises(Exception, match='failed for 3rd argument'):
414
+ y = self.blas_func(1, a, x, 1, y, trans=1, incx=3)
415
+
416
+ def test_y_stride(self):
417
+ alpha, beta, a, x, y = self.get_data(y_stride=2)
418
+ desired_y = y.copy()
419
+ desired_y[::2] = alpha*matrixmultiply(a, x)+beta*y[::2]
420
+ y = self.blas_func(alpha, a, x, beta, y, incy=2)
421
+ assert_array_almost_equal(desired_y, y)
422
+
423
+ def test_y_stride_transpose(self):
424
+ alpha, beta, a, x, y = self.get_data(y_stride=2)
425
+ desired_y = y.copy()
426
+ desired_y[::2] = alpha*matrixmultiply(transpose(a), x)+beta*y[::2]
427
+ y = self.blas_func(alpha, a, x, beta, y, trans=1, incy=2)
428
+ assert_array_almost_equal(desired_y, y)
429
+
430
+ def test_y_stride_assert(self):
431
+ # What is the use of this test?
432
+ alpha, beta, a, x, y = self.get_data(y_stride=2)
433
+ with pytest.raises(Exception, match='failed for 2nd keyword'):
434
+ y = self.blas_func(1, a, x, 1, y, trans=0, incy=3)
435
+ with pytest.raises(Exception, match='failed for 2nd keyword'):
436
+ y = self.blas_func(1, a, x, 1, y, trans=1, incy=3)
437
+
438
+
439
+ try:
440
+ class TestSgemv(BaseGemv):
441
+ blas_func = fblas.sgemv
442
+ dtype = float32
443
+
444
+ @pytest.mark.skipif(sys.platform != 'darwin', reason="MacOS specific test")
445
+ def test_sgemv_on_osx(self):
446
+ def aligned_array(shape, align, dtype, order='C'):
447
+ # Make array shape `shape` with aligned at `align` bytes
448
+ d = dtype()
449
+ # Make array of correct size with `align` extra bytes
450
+ N = np.prod(shape)
451
+ tmp = np.zeros(N * d.nbytes + align, dtype=np.uint8)
452
+ address = tmp.__array_interface__["data"][0]
453
+ # Find offset into array giving desired alignment
454
+ for offset in range(align):
455
+ if (address + offset) % align == 0:
456
+ break
457
+ tmp = tmp[offset:offset+N*d.nbytes].view(dtype=dtype)
458
+ return tmp.reshape(shape, order=order)
459
+
460
+ def as_aligned(arr, align, dtype, order='C'):
461
+ # Copy `arr` into an aligned array with same shape
462
+ aligned = aligned_array(arr.shape, align, dtype, order)
463
+ aligned[:] = arr[:]
464
+ return aligned
465
+
466
+ def assert_dot_close(A, X, desired):
467
+ assert_allclose(self.blas_func(1.0, A, X), desired,
468
+ rtol=1e-5, atol=1e-7)
469
+
470
+ testdata = product((15, 32), (10000,), (200, 89), ('C', 'F'))
471
+ rng = np.random.default_rng(1234)
472
+ for align, m, n, a_order in testdata:
473
+ A_d = rng.random((m, n))
474
+ X_d = rng.random(n)
475
+ desired = np.dot(A_d, X_d)
476
+ # Calculation with aligned single precision
477
+ A_f = as_aligned(A_d, align, np.float32, order=a_order)
478
+ X_f = as_aligned(X_d, align, np.float32, order=a_order)
479
+ assert_dot_close(A_f, X_f, desired)
480
+
481
+ except AttributeError:
482
+ class TestSgemv:
483
+ pass
484
+
485
+
486
+ class TestDgemv(BaseGemv):
487
+ blas_func = fblas.dgemv
488
+ dtype = float64
489
+
490
+
491
+ try:
492
+ class TestCgemv(BaseGemv):
493
+ blas_func = fblas.cgemv
494
+ dtype = complex64
495
+ except AttributeError:
496
+ class TestCgemv:
497
+ pass
498
+
499
+
500
+ class TestZgemv(BaseGemv):
501
+ blas_func = fblas.zgemv
502
+ dtype = complex128
503
+
504
+
505
+ """
506
+ ##################################################
507
+ ### Test blas ?ger
508
+ ### This will be a mess to test all cases.
509
+
510
+ class BaseGer:
511
+ def get_data(self,x_stride=1,y_stride=1):
512
+ rng = np.random.default_rng(1234)
513
+ alpha = array(1., dtype = self.dtype)
514
+ a = rng.normal(0.,1.,(3,3)).astype(self.dtype)
515
+ x = arange(shape(a)[0]*x_stride,dtype=self.dtype)
516
+ y = arange(shape(a)[1]*y_stride,dtype=self.dtype)
517
+ return alpha,a,x,y
518
+ def test_simple(self):
519
+ alpha,a,x,y = self.get_data()
520
+ # transpose takes care of Fortran vs. C(and Python) memory layout
521
+ desired_a = alpha*transpose(x[:,newaxis]*y) + a
522
+ self.blas_func(x,y,a)
523
+ assert_array_almost_equal(desired_a,a)
524
+ def test_x_stride(self):
525
+ alpha,a,x,y = self.get_data(x_stride=2)
526
+ desired_a = alpha*transpose(x[::2,newaxis]*y) + a
527
+ self.blas_func(x,y,a,incx=2)
528
+ assert_array_almost_equal(desired_a,a)
529
+ def test_x_stride_assert(self):
530
+ alpha,a,x,y = self.get_data(x_stride=2)
531
+ with pytest.raises(ValueError, match='foo'):
532
+ self.blas_func(x,y,a,incx=3)
533
+ def test_y_stride(self):
534
+ alpha,a,x,y = self.get_data(y_stride=2)
535
+ desired_a = alpha*transpose(x[:,newaxis]*y[::2]) + a
536
+ self.blas_func(x,y,a,incy=2)
537
+ assert_array_almost_equal(desired_a,a)
538
+
539
+ def test_y_stride_assert(self):
540
+ alpha,a,x,y = self.get_data(y_stride=2)
541
+ with pytest.raises(ValueError, match='foo'):
542
+ self.blas_func(a,x,y,incy=3)
543
+
544
+ class TestSger(BaseGer):
545
+ blas_func = fblas.sger
546
+ dtype = float32
547
+ class TestDger(BaseGer):
548
+ blas_func = fblas.dger
549
+ dtype = float64
550
+ """
551
+ ##################################################
552
+ # Test blas ?gerc
553
+ # This will be a mess to test all cases.
554
+
555
+ """
556
+ class BaseGerComplex(BaseGer):
557
+ def get_data(self,x_stride=1,y_stride=1):
558
+ rng = np.random.default_rng(1234)
559
+ alpha = array(1+1j, dtype = self.dtype)
560
+ a = rng.normal(0.,1.,(3,3)).astype(self.dtype)
561
+ a = a + rng.normal(0.,1.,(3,3)) * array(1j, dtype = self.dtype)
562
+ x = rng.normal(0.,1.,shape(a)[0]*x_stride).astype(self.dtype)
563
+ x = x + x * array(1j, dtype = self.dtype)
564
+ y = rng.normal(0.,1.,shape(a)[1]*y_stride).astype(self.dtype)
565
+ y = y + y * array(1j, dtype = self.dtype)
566
+ return alpha,a,x,y
567
+ def test_simple(self):
568
+ alpha,a,x,y = self.get_data()
569
+ # transpose takes care of Fortran vs. C(and Python) memory layout
570
+ a = a * array(0.,dtype = self.dtype)
571
+ #desired_a = alpha*transpose(x[:,newaxis]*self.transform(y)) + a
572
+ desired_a = alpha*transpose(x[:,newaxis]*y) + a
573
+ #self.blas_func(x,y,a,alpha = alpha)
574
+ fblas.cgeru(x,y,a,alpha = alpha)
575
+ assert_array_almost_equal(desired_a,a)
576
+
577
+ #def test_x_stride(self):
578
+ # alpha,a,x,y = self.get_data(x_stride=2)
579
+ # desired_a = alpha*transpose(x[::2,newaxis]*self.transform(y)) + a
580
+ # self.blas_func(x,y,a,incx=2)
581
+ # assert_array_almost_equal(desired_a,a)
582
+ #def test_y_stride(self):
583
+ # alpha,a,x,y = self.get_data(y_stride=2)
584
+ # desired_a = alpha*transpose(x[:,newaxis]*self.transform(y[::2])) + a
585
+ # self.blas_func(x,y,a,incy=2)
586
+ # assert_array_almost_equal(desired_a,a)
587
+
588
+ class TestCgeru(BaseGerComplex):
589
+ blas_func = fblas.cgeru
590
+ dtype = complex64
591
+ def transform(self,x):
592
+ return x
593
+ class TestZgeru(BaseGerComplex):
594
+ blas_func = fblas.zgeru
595
+ dtype = complex128
596
+ def transform(self,x):
597
+ return x
598
+
599
+ class TestCgerc(BaseGerComplex):
600
+ blas_func = fblas.cgerc
601
+ dtype = complex64
602
+ def transform(self,x):
603
+ return conjugate(x)
604
+
605
+ class TestZgerc(BaseGerComplex):
606
+ blas_func = fblas.zgerc
607
+ dtype = complex128
608
+ def transform(self,x):
609
+ return conjugate(x)
610
+ """
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_interpolative.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ******************************************************************************
2
+ # Copyright (C) 2013 Kenneth L. Ho
3
+ # Redistribution and use in source and binary forms, with or without
4
+ # modification, are permitted provided that the following conditions are met:
5
+ #
6
+ # Redistributions of source code must retain the above copyright notice, this
7
+ # list of conditions and the following disclaimer. Redistributions in binary
8
+ # form must reproduce the above copyright notice, this list of conditions and
9
+ # the following disclaimer in the documentation and/or other materials
10
+ # provided with the distribution.
11
+ #
12
+ # None of the names of the copyright holders may be used to endorse or
13
+ # promote products derived from this software without specific prior written
14
+ # permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+ # ******************************************************************************
28
+
29
+ import scipy.linalg.interpolative as pymatrixid
30
+ import numpy as np
31
+ from scipy.linalg import hilbert, svdvals, norm
32
+ from scipy.sparse.linalg import aslinearoperator
33
+ from scipy.linalg.interpolative import interp_decomp
34
+
35
+ from numpy.testing import (assert_, assert_allclose, assert_equal,
36
+ assert_array_equal)
37
+ import pytest
38
+ from pytest import raises as assert_raises
39
+
40
+
41
+ @pytest.fixture()
42
+ def eps():
43
+ yield 1e-12
44
+
45
+
46
+ @pytest.fixture()
47
+ def rng():
48
+ rng = np.random.default_rng(1718313768084012)
49
+ yield rng
50
+
51
+
52
+ @pytest.fixture(params=[np.float64, np.complex128])
53
+ def A(request):
54
+ # construct Hilbert matrix
55
+ # set parameters
56
+ n = 300
57
+ yield hilbert(n).astype(request.param)
58
+
59
+
60
+ @pytest.fixture()
61
+ def L(A):
62
+ yield aslinearoperator(A)
63
+
64
+
65
+ @pytest.fixture()
66
+ def rank(A, eps):
67
+ S = np.linalg.svd(A, compute_uv=False)
68
+ try:
69
+ rank = np.nonzero(S < eps)[0][0]
70
+ except IndexError:
71
+ rank = A.shape[0]
72
+ return rank
73
+
74
+
75
+ class TestInterpolativeDecomposition:
76
+
77
+ @pytest.mark.parametrize(
78
+ "rand,lin_op",
79
+ [(False, False), (True, False), (True, True)])
80
+ def test_real_id_fixed_precision(self, A, L, eps, rand, lin_op, rng):
81
+ # Test ID routines on a Hilbert matrix.
82
+ A_or_L = A if not lin_op else L
83
+
84
+ k, idx, proj = pymatrixid.interp_decomp(A_or_L, eps, rand=rand, rng=rng)
85
+ B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj)
86
+ assert_allclose(A, B, rtol=eps, atol=1e-08)
87
+
88
+ @pytest.mark.parametrize(
89
+ "rand,lin_op",
90
+ [(False, False), (True, False), (True, True)])
91
+ def test_real_id_fixed_rank(self, A, L, eps, rank, rand, lin_op, rng):
92
+ k = rank
93
+ A_or_L = A if not lin_op else L
94
+
95
+ idx, proj = pymatrixid.interp_decomp(A_or_L, k, rand=rand, rng=rng)
96
+ B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj)
97
+ assert_allclose(A, B, rtol=eps, atol=1e-08)
98
+
99
+ @pytest.mark.parametrize("rand,lin_op", [(False, False)])
100
+ def test_real_id_skel_and_interp_matrices(
101
+ self, A, L, eps, rank, rand, lin_op, rng):
102
+ k = rank
103
+ A_or_L = A if not lin_op else L
104
+
105
+ idx, proj = pymatrixid.interp_decomp(A_or_L, k, rand=rand, rng=rng)
106
+ P = pymatrixid.reconstruct_interp_matrix(idx, proj)
107
+ B = pymatrixid.reconstruct_skel_matrix(A, k, idx)
108
+ assert_allclose(B, A[:, idx[:k]], rtol=eps, atol=1e-08)
109
+ assert_allclose(B @ P, A, rtol=eps, atol=1e-08)
110
+
111
+ @pytest.mark.parametrize(
112
+ "rand,lin_op",
113
+ [(False, False), (True, False), (True, True)])
114
+ def test_svd_fixed_precision(self, A, L, eps, rand, lin_op, rng):
115
+ A_or_L = A if not lin_op else L
116
+
117
+ U, S, V = pymatrixid.svd(A_or_L, eps, rand=rand, rng=rng)
118
+ B = U * S @ V.T.conj()
119
+ assert_allclose(A, B, rtol=eps, atol=1e-08)
120
+
121
+ @pytest.mark.parametrize(
122
+ "rand,lin_op",
123
+ [(False, False), (True, False), (True, True)])
124
+ def test_svd_fixed_rank(self, A, L, eps, rank, rand, lin_op, rng):
125
+ k = rank
126
+ A_or_L = A if not lin_op else L
127
+
128
+ U, S, V = pymatrixid.svd(A_or_L, k, rand=rand, rng=rng)
129
+ B = U * S @ V.T.conj()
130
+ assert_allclose(A, B, rtol=eps, atol=1e-08)
131
+
132
+ def test_id_to_svd(self, A, eps, rank):
133
+ k = rank
134
+
135
+ idx, proj = pymatrixid.interp_decomp(A, k, rand=False)
136
+ U, S, V = pymatrixid.id_to_svd(A[:, idx[:k]], idx, proj)
137
+ B = U * S @ V.T.conj()
138
+ assert_allclose(A, B, rtol=eps, atol=1e-08)
139
+
140
+ def test_estimate_spectral_norm(self, A, rng):
141
+ s = svdvals(A)
142
+ norm_2_est = pymatrixid.estimate_spectral_norm(A, rng=rng)
143
+ assert_allclose(norm_2_est, s[0], rtol=1e-6, atol=1e-8)
144
+
145
+ def test_estimate_spectral_norm_diff(self, A, rng):
146
+ B = A.copy()
147
+ B[:, 0] *= 1.2
148
+ s = svdvals(A - B)
149
+ norm_2_est = pymatrixid.estimate_spectral_norm_diff(A, B, rng=rng)
150
+ assert_allclose(norm_2_est, s[0], rtol=1e-6, atol=1e-8)
151
+
152
+ def test_rank_estimates_array(self, A, rng):
153
+ B = np.array([[1, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=A.dtype)
154
+
155
+ for M in [A, B]:
156
+ rank_tol = 1e-9
157
+ rank_np = np.linalg.matrix_rank(M, norm(M, 2) * rank_tol)
158
+ rank_est = pymatrixid.estimate_rank(M, rank_tol, rng=rng)
159
+ assert_(rank_est >= rank_np)
160
+ assert_(rank_est <= rank_np + 10)
161
+
162
+ def test_rank_estimates_lin_op(self, A, rng):
163
+ B = np.array([[1, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=A.dtype)
164
+
165
+ for M in [A, B]:
166
+ ML = aslinearoperator(M)
167
+ rank_tol = 1e-9
168
+ rank_np = np.linalg.matrix_rank(M, norm(M, 2) * rank_tol)
169
+ rank_est = pymatrixid.estimate_rank(ML, rank_tol, rng=rng)
170
+ assert_(rank_est >= rank_np - 4)
171
+ assert_(rank_est <= rank_np + 4)
172
+
173
+ def test_badcall(self):
174
+ A = hilbert(5).astype(np.float32)
175
+ with assert_raises(ValueError):
176
+ pymatrixid.interp_decomp(A, 1e-6, rand=False)
177
+
178
+ def test_rank_too_large(self):
179
+ # svd(array, k) should not segfault
180
+ a = np.ones((4, 3))
181
+ with assert_raises(ValueError):
182
+ pymatrixid.svd(a, 4)
183
+
184
+ def test_full_rank(self):
185
+ eps = 1.0e-12
186
+ rng = np.random.default_rng(1234)
187
+ # fixed precision
188
+ A = rng.random((16, 8))
189
+ k, idx, proj = pymatrixid.interp_decomp(A, eps)
190
+ assert_equal(k, A.shape[1])
191
+
192
+ P = pymatrixid.reconstruct_interp_matrix(idx, proj)
193
+ B = pymatrixid.reconstruct_skel_matrix(A, k, idx)
194
+ assert_allclose(A, B @ P)
195
+
196
+ # fixed rank
197
+ idx, proj = pymatrixid.interp_decomp(A, k)
198
+
199
+ P = pymatrixid.reconstruct_interp_matrix(idx, proj)
200
+ B = pymatrixid.reconstruct_skel_matrix(A, k, idx)
201
+ assert_allclose(A, B @ P)
202
+
203
+ @pytest.mark.parametrize("dtype", [np.float64, np.complex128])
204
+ @pytest.mark.parametrize("rand", [True, False])
205
+ @pytest.mark.parametrize("eps", [1, 0.1])
206
+ def test_bug_9793(self, dtype, rand, eps):
207
+ A = np.array([[-1, -1, -1, 0, 0, 0],
208
+ [0, 0, 0, 1, 1, 1],
209
+ [1, 0, 0, 1, 0, 0],
210
+ [0, 1, 0, 0, 1, 0],
211
+ [0, 0, 1, 0, 0, 1]],
212
+ dtype=dtype, order="C")
213
+ B = A.copy()
214
+ interp_decomp(A.T, eps, rand=rand)
215
+ assert_array_equal(A, B)
216
+
217
+ def test_svd_aslinearoperator_shape_check(self):
218
+ # See gh-issue #22451
219
+ rng = np.random.default_rng(1744580941832515)
220
+ x = rng.uniform(size=[7, 5])
221
+ xl = aslinearoperator(x)
222
+ u, s, v = pymatrixid.svd(xl, 3)
223
+ assert_equal(u.shape, (7, 3))
224
+ assert_equal(s.shape, (3,))
225
+ assert_equal(v.shape, (5, 3))
226
+
227
+ x = rng.uniform(size=[4, 9])
228
+ xl = aslinearoperator(x)
229
+ u, s, v = pymatrixid.svd(xl, 2)
230
+ assert_equal(u.shape, (4, 2))
231
+ assert_equal(s.shape, (2,))
232
+ assert_equal(v.shape, (9, 2))
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_lapack.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_matfuncs.py ADDED
@@ -0,0 +1,1149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Created by: Pearu Peterson, March 2002
3
+ #
4
+ """ Test functions for linalg.matfuncs module
5
+
6
+ """
7
+ import functools
8
+ import pytest
9
+ import warnings
10
+
11
+ import numpy as np
12
+ from numpy import array, identity, sqrt
13
+ from numpy.testing import (assert_array_almost_equal, assert_allclose, assert_,
14
+ assert_array_less, assert_array_equal)
15
+
16
+ import scipy.linalg
17
+ from scipy.linalg import (funm, signm, logm, sqrtm, fractional_matrix_power,
18
+ expm, expm_frechet, expm_cond, norm, khatri_rao,
19
+ cosm, sinm, tanm, coshm, sinhm, tanhm)
20
+
21
+ from scipy.linalg import _matfuncs_inv_ssq
22
+ from scipy.linalg._matfuncs_inv_ssq import LogmExactlySingularWarning
23
+ import scipy.linalg._expm_frechet
24
+ from scipy.linalg import LinAlgWarning
25
+ from scipy.optimize import minimize
26
+
27
+
28
+ def _get_al_mohy_higham_2012_experiment_1():
29
+ """
30
+ Return the test matrix from Experiment (1) of [1]_.
31
+
32
+ References
33
+ ----------
34
+ .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2012)
35
+ "Improved Inverse Scaling and Squaring Algorithms
36
+ for the Matrix Logarithm."
37
+ SIAM Journal on Scientific Computing, 34 (4). C152-C169.
38
+ ISSN 1095-7197
39
+
40
+ """
41
+ A = np.array([
42
+ [3.2346e-1, 3e4, 3e4, 3e4],
43
+ [0, 3.0089e-1, 3e4, 3e4],
44
+ [0, 0, 3.2210e-1, 3e4],
45
+ [0, 0, 0, 3.0744e-1]], dtype=float)
46
+ return A
47
+
48
+
49
+ class TestSignM:
50
+
51
+ def test_nils(self):
52
+ a = array([[29.2, -24.2, 69.5, 49.8, 7.],
53
+ [-9.2, 5.2, -18., -16.8, -2.],
54
+ [-10., 6., -20., -18., -2.],
55
+ [-9.6, 9.6, -25.5, -15.4, -2.],
56
+ [9.8, -4.8, 18., 18.2, 2.]])
57
+ cr = array([[11.94933333,-2.24533333,15.31733333,21.65333333,-2.24533333],
58
+ [-3.84266667,0.49866667,-4.59066667,-7.18666667,0.49866667],
59
+ [-4.08,0.56,-4.92,-7.6,0.56],
60
+ [-4.03466667,1.04266667,-5.59866667,-7.02666667,1.04266667],
61
+ [4.15733333,-0.50133333,4.90933333,7.81333333,-0.50133333]])
62
+ r = signm(a)
63
+ assert_array_almost_equal(r,cr)
64
+
65
+ def test_defective1(self):
66
+ a = array([[0.0,1,0,0],[1,0,1,0],[0,0,0,1],[0,0,1,0]])
67
+ signm(a)
68
+ #XXX: what would be the correct result?
69
+
70
+ def test_defective2(self):
71
+ a = array((
72
+ [29.2,-24.2,69.5,49.8,7.0],
73
+ [-9.2,5.2,-18.0,-16.8,-2.0],
74
+ [-10.0,6.0,-20.0,-18.0,-2.0],
75
+ [-9.6,9.6,-25.5,-15.4,-2.0],
76
+ [9.8,-4.8,18.0,18.2,2.0]))
77
+ signm(a)
78
+ #XXX: what would be the correct result?
79
+
80
+ def test_defective3(self):
81
+ a = array([[-2., 25., 0., 0., 0., 0., 0.],
82
+ [0., -3., 10., 3., 3., 3., 0.],
83
+ [0., 0., 2., 15., 3., 3., 0.],
84
+ [0., 0., 0., 0., 15., 3., 0.],
85
+ [0., 0., 0., 0., 3., 10., 0.],
86
+ [0., 0., 0., 0., 0., -2., 25.],
87
+ [0., 0., 0., 0., 0., 0., -3.]])
88
+ signm(a)
89
+ #XXX: what would be the correct result?
90
+
91
+ @pytest.mark.parametrize('dtype', [np.float32, np.float64,
92
+ np.complex64, np.complex128])
93
+ def test_signm_dtype_preservation(self, dtype):
94
+ # gh-25657: signm upcast float32/complex64 for defective matrices
95
+ # (the iterative fall-through branch) while the non-defective branch
96
+ # preserved dtype. Output dtype must depend on input dtype, not values.
97
+ non_defective = np.array([[2, 1], [0, 3]], dtype=dtype) # distinct eigs
98
+ defective = np.array([[2, 1], [0, 2]], dtype=dtype) # repeated eig
99
+ assert signm(non_defective).dtype == dtype
100
+ assert signm(defective).dtype == dtype
101
+
102
+
103
+ class TestLogM:
104
+ @pytest.mark.filterwarnings("ignore:.*inaccurate.*:RuntimeWarning")
105
+ def test_nils(self):
106
+ a = array([[-2., 25., 0., 0., 0., 0., 0.],
107
+ [0., -3., 10., 3., 3., 3., 0.],
108
+ [0., 0., 2., 15., 3., 3., 0.],
109
+ [0., 0., 0., 0., 15., 3., 0.],
110
+ [0., 0., 0., 0., 3., 10., 0.],
111
+ [0., 0., 0., 0., 0., -2., 25.],
112
+ [0., 0., 0., 0., 0., 0., -3.]])
113
+ m = (identity(7)*3.1+0j)-a
114
+ logm(m)
115
+ #XXX: what would be the correct result?
116
+
117
+ @pytest.mark.filterwarnings("ignore:.*inaccurate.*:RuntimeWarning")
118
+ def test_al_mohy_higham_2012_experiment_1_logm(self):
119
+ # The logm completes the round trip successfully.
120
+ # Note that the expm leg of the round trip is badly conditioned.
121
+ A = _get_al_mohy_higham_2012_experiment_1()
122
+ A_logm = logm(A)
123
+ A_round_trip = expm(A_logm)
124
+ assert_allclose(A_round_trip, A, rtol=5e-5, atol=1e-14)
125
+
126
+ def test_al_mohy_higham_2012_experiment_1_funm_log(self):
127
+ # The raw funm with np.log does not complete the round trip.
128
+ # Note that the expm leg of the round trip is badly conditioned.
129
+ A = _get_al_mohy_higham_2012_experiment_1()
130
+ A_funm_log = funm(A, np.log)
131
+ A_round_trip = expm(A_funm_log)
132
+ assert_(not np.allclose(A_round_trip, A, rtol=1e-5, atol=1e-14))
133
+
134
+ def test_round_trip_random_float(self):
135
+ rng = np.random.default_rng(1738098768840254)
136
+ for n in range(1, 6):
137
+ M_unscaled = rng.uniform(size=(n, n))
138
+ for scale in np.logspace(-4, 4, 9):
139
+ M = M_unscaled * scale
140
+
141
+ # Eigenvalues are related to the branch cut.
142
+ W = np.linalg.eigvals(M)
143
+ err_msg = f'M:{M} eivals:{W}'
144
+
145
+ # Check sqrtm round trip because it is used within logm.
146
+ M_sqrtm = sqrtm(M)
147
+ M_sqrtm_round_trip = M_sqrtm @ M_sqrtm
148
+ assert_allclose(M_sqrtm_round_trip, M)
149
+
150
+ # Check logm round trip.
151
+ with warnings.catch_warnings():
152
+ warnings.simplefilter("ignore", RuntimeWarning)
153
+
154
+ M_logm = logm(M)
155
+ M_logm_round_trip = expm(M_logm)
156
+ assert_allclose(M_logm_round_trip, M, err_msg=err_msg)
157
+
158
+ def test_round_trip_random_complex(self):
159
+ rng = np.random.default_rng(1738098768840254)
160
+ for n in range(1, 6):
161
+ M_unscaled = (rng.standard_normal((n, n)) +
162
+ 1j*rng.standard_normal((n, n)))
163
+ for scale in np.logspace(-4, 4, 9):
164
+ M = M_unscaled * scale
165
+ M_logm = logm(M)
166
+ M_round_trip = expm(M_logm)
167
+ assert_allclose(M_round_trip, M)
168
+
169
+ def test_logm_type_preservation_and_conversion(self):
170
+ # The logm matrix function should preserve the type of a matrix
171
+ # whose eigenvalues are positive with zero imaginary part.
172
+ # Test this preservation for variously structured matrices.
173
+ complex_dtype_chars = ('F', 'D', 'G')
174
+ for matrix_as_list in (
175
+ [[1, 0], [0, 1]],
176
+ [[1, 0], [1, 1]],
177
+ [[2, 1], [1, 1]],
178
+ [[2, 3], [1, 2]]):
179
+
180
+ # check that the spectrum has the expected properties
181
+ W = scipy.linalg.eigvals(matrix_as_list)
182
+ assert_(not any(w.imag or w.real < 0 for w in W))
183
+
184
+ # check float type preservation
185
+ A = np.array(matrix_as_list, dtype=float)
186
+ A_logm = logm(A)
187
+ assert_(A_logm.dtype.char not in complex_dtype_chars)
188
+
189
+ # check complex type preservation
190
+ A = np.array(matrix_as_list, dtype=complex)
191
+ A_logm = logm(A)
192
+ assert_(A_logm.dtype.char in complex_dtype_chars)
193
+
194
+ # check float->complex type conversion for the matrix negation
195
+ A = -np.array(matrix_as_list, dtype=float)
196
+ A_logm = logm(A)
197
+ assert_(A_logm.dtype.char in complex_dtype_chars)
198
+
199
+ def test_complex_spectrum_real_logm(self):
200
+ # This matrix has complex eigenvalues and real logm.
201
+ # Its output dtype depends on its input dtype.
202
+ M = [[1, 1, 2], [2, 1, 1], [1, 2, 1]]
203
+ for dt in float, complex:
204
+ X = np.array(M, dtype=dt)
205
+ w = scipy.linalg.eigvals(X)
206
+ assert_(1e-2 < np.absolute(w.imag).sum())
207
+ Y = logm(X)
208
+ assert_(np.issubdtype(Y.dtype, np.inexact))
209
+ assert_allclose(expm(Y), X)
210
+
211
+ def test_real_mixed_sign_spectrum(self):
212
+ # These matrices have real eigenvalues with mixed signs.
213
+ # The output logm dtype is complex, regardless of input dtype.
214
+ for M in (
215
+ [[1, 0], [0, -1]],
216
+ [[0, 1], [1, 0]]):
217
+ for dt in float, complex:
218
+ A = np.array(M, dtype=dt)
219
+ A_logm, info = logm(A)
220
+ assert_(np.issubdtype(A_logm.dtype, np.complexfloating))
221
+
222
+ def test_exactly_singular(self):
223
+ A = np.array([[0, 0], [1j, 1j]])
224
+ B = np.asarray([[1, 1], [0, 0]])
225
+ for M in A, A.T, B, B.T:
226
+ with pytest.warns(_matfuncs_inv_ssq.LogmExactlySingularWarning):
227
+ L = logm(M)
228
+ E = expm(L)
229
+ assert_allclose(E, M, atol=1e-14)
230
+
231
+ def test_nearly_singular(self):
232
+ M = np.array([[1e-100]])
233
+ with pytest.warns(_matfuncs_inv_ssq.LogmNearlySingularWarning):
234
+ L = logm(M)
235
+ E = expm(L)
236
+ assert_allclose(E, M, atol=1e-14)
237
+
238
+ def test_opposite_sign_complex_eigenvalues(self):
239
+ # See gh-6113
240
+ E = [[0, 1], [-1, 0]]
241
+ L = [[0, np.pi*0.5], [-np.pi*0.5, 0]]
242
+ assert_allclose(expm(L), E, atol=1e-14)
243
+ assert_allclose(logm(E), L, atol=1e-14)
244
+ E = [[1j, 4], [0, -1j]]
245
+ L = [[1j*np.pi*0.5, 2*np.pi], [0, -1j*np.pi*0.5]]
246
+ assert_allclose(expm(L), E, atol=1e-14)
247
+ assert_allclose(logm(E), L, atol=1e-14)
248
+ E = [[1j, 0], [0, -1j]]
249
+ L = [[1j*np.pi*0.5, 0], [0, -1j*np.pi*0.5]]
250
+ assert_allclose(expm(L), E, atol=1e-14)
251
+ assert_allclose(logm(E), L, atol=1e-14)
252
+
253
+ def test_readonly(self):
254
+ n = 5
255
+ a = np.ones((n, n)) + np.identity(n)
256
+ a.flags.writeable = False
257
+ logm(a)
258
+
259
+ @pytest.mark.xfail(reason="ValueError: attempt to get argmax of an empty sequence")
260
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
261
+ def test_empty(self, dt):
262
+ a = np.empty((0, 0), dtype=dt)
263
+ log_a = logm(a)
264
+ a0 = np.eye(2, dtype=dt)
265
+ log_a0 = logm(a0)
266
+
267
+ assert log_a.shape == (0, 0)
268
+ assert log_a.dtype == log_a0.dtype
269
+
270
+ @pytest.mark.parametrize('dtype', [int, float, np.float32, complex, np.complex64])
271
+ def test_no_ZeroDivisionError(self, dtype):
272
+ # gh-17136 reported inconsistent behavior in `logm` depending on input dtype:
273
+ # sometimes it raised an error, and sometimes it printed a warning message.
274
+ # check that this is resolved and that the warning is emitted properly.
275
+ with (pytest.warns(RuntimeWarning, match="logm result may be inaccurate"),
276
+ pytest.warns(LogmExactlySingularWarning)):
277
+ logm(np.zeros((2, 2), dtype=dtype))
278
+
279
+
280
+ class TestSqrtM:
281
+
282
+ def test_round_trip_random_float(self):
283
+ rng = np.random.default_rng(1738151906092735)
284
+ for n in range(1, 6):
285
+ M_unscaled = rng.standard_normal((n, n))
286
+ for scale in np.logspace(-4, 4, 9):
287
+ M = M_unscaled * scale
288
+ M_sqrtm = sqrtm(M)
289
+ M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm)
290
+ assert_allclose(M_sqrtm_round_trip, M)
291
+
292
+ def test_round_trip_random_complex(self):
293
+ rng = np.random.default_rng(1738151906092736)
294
+ for n in range(1, 6):
295
+ M_unscaled = (rng.standard_normal((n, n)) +
296
+ 1j * rng.standard_normal((n, n)))
297
+ for scale in np.logspace(-4, 4, 9):
298
+ M = M_unscaled * scale
299
+ M_sqrtm = sqrtm(M)
300
+ M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm)
301
+ assert_allclose(M_sqrtm_round_trip, M)
302
+
303
+ def test_bad(self):
304
+ # See https://web.archive.org/web/20051220232650/http://www.maths.man.ac.uk/~nareports/narep336.ps.gz
305
+ e = 2**-5
306
+ se = sqrt(e)
307
+ a = array([[1.0,0,0,1],
308
+ [0,e,0,0],
309
+ [0,0,e,0],
310
+ [0,0,0,1]])
311
+ sa = array([[1,0,0,0.5],
312
+ [0,se,0,0],
313
+ [0,0,se,0],
314
+ [0,0,0,1]])
315
+ assert_array_almost_equal(sa @ sa, a)
316
+ # Check default sqrtm.
317
+ esa = sqrtm(a)
318
+ assert_array_almost_equal(esa @ esa, a)
319
+
320
+ def test_sqrtm_type_preservation_and_conversion(self):
321
+ # The sqrtm matrix function should preserve the type of a matrix
322
+ # whose eigenvalues are nonnegative with zero imaginary part.
323
+ # Test this preservation for variously structured matrices.
324
+ complex_dtype_chars = ('F', 'D', 'G')
325
+ for matrix_as_list in (
326
+ [[1, 0], [0, 1]],
327
+ [[1, 0], [1, 1]],
328
+ [[2, 1], [1, 1]],
329
+ [[2, 3], [1, 2]],
330
+ [[1, 1], [1, 1]]):
331
+
332
+ # check that the spectrum has the expected properties
333
+ W = scipy.linalg.eigvals(matrix_as_list)
334
+ assert_(not any(w.imag or w.real < 0 for w in W))
335
+
336
+ # Last test matrix is singular so suppress the warning
337
+ with warnings.catch_warnings():
338
+ warnings.simplefilter("ignore", LinAlgWarning)
339
+
340
+ # check float type preservation
341
+ A = np.array(matrix_as_list, dtype=float)
342
+ A_sqrtm = sqrtm(A)
343
+ assert_(A_sqrtm.dtype.char not in complex_dtype_chars)
344
+
345
+ # check complex type preservation
346
+ A = np.array(matrix_as_list, dtype=complex)
347
+ A_sqrtm = sqrtm(A)
348
+ assert_(A_sqrtm.dtype.char in complex_dtype_chars)
349
+
350
+ # check float->complex type conversion for the matrix negation
351
+ A = -np.array(matrix_as_list, dtype=float)
352
+ A_sqrtm = sqrtm(A)
353
+ assert_(A_sqrtm.dtype.char in complex_dtype_chars)
354
+
355
+ def test_sqrtm_type_conversion_mixed_sign_or_complex_spectrum(self):
356
+ complex_dtype_chars = ('F', 'D', 'G')
357
+ for matrix_as_list in (
358
+ [[1, 0], [0, -1]],
359
+ [[0, 1], [1, 0]],
360
+ [[0, 1, 0], [0, 0, -1], [1, 0, 0]]):
361
+
362
+ # check that the spectrum has the expected properties
363
+ W = scipy.linalg.eigvals(matrix_as_list)
364
+ assert_(any(w.imag or w.real < 0 for w in W))
365
+
366
+ # check complex->complex
367
+ A = np.array(matrix_as_list, dtype=complex)
368
+ A_sqrtm = sqrtm(A)
369
+ assert_(A_sqrtm.dtype.char in complex_dtype_chars)
370
+
371
+ # check float->complex
372
+ A = np.array(matrix_as_list, dtype=float)
373
+ A_sqrtm = sqrtm(A)
374
+ assert_(A_sqrtm.dtype.char in complex_dtype_chars)
375
+
376
+ def test_al_mohy_higham_2012_experiment_1(self):
377
+ # Matrix square root of a tricky upper triangular matrix.
378
+ A = _get_al_mohy_higham_2012_experiment_1()
379
+ A_sqrtm = sqrtm(A)
380
+ A_round_trip = A_sqrtm @ A_sqrtm
381
+ assert_allclose(A_round_trip, A, rtol=1e-5)
382
+ assert_allclose(np.tril(A_round_trip), np.tril(A))
383
+
384
+ def test_strict_upper_triangular(self):
385
+ # This matrix has no square root but upper triangular hence upper
386
+ # triangle will be filled with junk values.
387
+ for dt in int, float:
388
+ A = np.array([
389
+ [0, 3, 0, 0],
390
+ [0, 0, 3, 0],
391
+ [0, 0, 0, 3],
392
+ [0, 0, 0, 0]], dtype=dt)
393
+ with warnings.catch_warnings():
394
+ warnings.simplefilter("ignore", LinAlgWarning)
395
+
396
+ A_sqrtm = sqrtm(A)
397
+ assert_allclose(np.tril(A_sqrtm), np.zeros((4, 4)))
398
+ assert np.isnan(A_sqrtm).any()
399
+ assert np.isinf(A_sqrtm).any()
400
+
401
+ # Future edit: This squareroot is not possible to find algorithmically
402
+ # with the current methods. Now sqrtm docstring has another example of
403
+ # such matrix whose squareroot is not a polynomial in it. Hence no need
404
+ # to test it here.
405
+ """
406
+ def test_weird_matrix(self):
407
+ # The square root of matrix B exists.
408
+ for dt in int, float:
409
+ A = np.array([
410
+ [0, 0, 1],
411
+ [0, 0, 0],
412
+ [0, 1, 0]], dtype=dt)
413
+ B = np.array([
414
+ [0, 1, 0],
415
+ [0, 0, 0],
416
+ [0, 0, 0]], dtype=dt)
417
+ assert_array_equal(B, A @ A)
418
+
419
+ # But scipy sqrtm is not clever enough to find it.
420
+ B_sqrtm, info = sqrtm(B, disp=False)
421
+ assert_(np.isnan(B_sqrtm).all())
422
+ """
423
+
424
+ def test_opposite_sign_complex_eigenvalues(self):
425
+ M = [[2j, 4], [0, -2j]]
426
+ R = [[1+1j, 2], [0, 1-1j]]
427
+ assert_allclose(np.dot(R, R), M, atol=1e-14)
428
+ assert_allclose(sqrtm(M), R, atol=1e-14)
429
+
430
+ def test_gh4866(self):
431
+ M = np.array([[1, 0, 0, 1],
432
+ [0, 0, 0, 0],
433
+ [0, 0, 0, 0],
434
+ [1, 0, 0, 1]])
435
+ R = np.array([[sqrt(0.5), 0, 0, sqrt(0.5)],
436
+ [0, 0, 0, 0],
437
+ [0, 0, 0, 0],
438
+ [sqrt(0.5), 0, 0, sqrt(0.5)]])
439
+ assert_allclose(R @ R, M, atol=1e-14)
440
+ with warnings.catch_warnings():
441
+ warnings.simplefilter("ignore", LinAlgWarning)
442
+
443
+ assert_allclose(sqrtm(M), R, atol=1e-14)
444
+
445
+ def test_gh5336(self):
446
+ M = np.diag([2, 1, 0])
447
+ R = np.diag([sqrt(2), 1, 0])
448
+ assert_allclose(R @ R, M, atol=1e-14)
449
+ with warnings.catch_warnings():
450
+ warnings.filterwarnings("ignore", category=LinAlgWarning)
451
+ assert_allclose(sqrtm(M), R, atol=1e-14)
452
+
453
+ def test_gh7839(self):
454
+ M = np.zeros((2, 2))
455
+ R = np.zeros((2, 2))
456
+ # Catch and silence LinAlgWarning
457
+ with warnings.catch_warnings():
458
+ warnings.filterwarnings("ignore", category=LinAlgWarning)
459
+
460
+ assert_allclose(sqrtm(M), R, atol=1e-14)
461
+
462
+ def test_gh17918(self):
463
+ M = np.empty((19, 19))
464
+ M.fill(0.94)
465
+ np.fill_diagonal(M, 1)
466
+ assert np.isrealobj(sqrtm(M))
467
+
468
+ def test_gh23278(self):
469
+ M = np.array([[1., 0., 0.], [0, 1, -1j], [0, 1j, 2]])
470
+ sq = sqrtm(M)
471
+ assert_allclose(sq @ sq, M, atol=1e-14)
472
+ sq = sqrtm(M.astype(np.complex64))
473
+ assert_allclose(sq @ sq, M, atol=1e-6)
474
+
475
+ def test_data_size_preservation_uint_in_float_out(self):
476
+ M = np.eye(10, dtype=np.uint8)
477
+ assert sqrtm(M).dtype == np.float64
478
+ M = np.eye(10, dtype=np.uint16)
479
+ assert sqrtm(M).dtype == np.float64
480
+ M = np.eye(10, dtype=np.uint32)
481
+ assert sqrtm(M).dtype == np.float64
482
+ M = np.eye(10, dtype=np.uint64)
483
+ assert sqrtm(M).dtype == np.float64
484
+
485
+ def test_data_size_preservation_int_in_float_out(self):
486
+ M = np.eye(10, dtype=np.int8)
487
+ assert sqrtm(M).dtype == np.float64
488
+ M = np.eye(10, dtype=np.int16)
489
+ assert sqrtm(M).dtype == np.float64
490
+ M = np.eye(10, dtype=np.int32)
491
+ assert sqrtm(M).dtype == np.float64
492
+ M = np.eye(10, dtype=np.int64)
493
+ assert sqrtm(M).dtype == np.float64
494
+
495
+ def test_data_size_preservation_int_in_comp_out(self):
496
+ M = np.array([[2, 4], [0, -2]], dtype=np.int8)
497
+ assert sqrtm(M).dtype == np.complex128
498
+ M = np.array([[2, 4], [0, -2]], dtype=np.int16)
499
+ assert sqrtm(M).dtype == np.complex128
500
+ M = np.array([[2, 4], [0, -2]], dtype=np.int32)
501
+ assert sqrtm(M).dtype == np.complex128
502
+ M = np.array([[2, 4], [0, -2]], dtype=np.int64)
503
+ assert sqrtm(M).dtype == np.complex128
504
+
505
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
506
+ def test_data_size_preservation_float_in_float_out(self):
507
+ M = np.eye(10, dtype=np.float16)
508
+ assert sqrtm(M).dtype == np.float32
509
+ M = np.eye(10, dtype=np.float32)
510
+ assert sqrtm(M).dtype == np.float32
511
+ M = np.eye(10, dtype=np.float64)
512
+ assert sqrtm(M).dtype == np.float64
513
+ if hasattr(np, 'float128'):
514
+ M = np.eye(10, dtype=np.float128)
515
+ assert sqrtm(M).dtype == np.float64
516
+
517
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
518
+ def test_data_size_preservation_float_in_comp_out(self):
519
+ M = np.array([[2, 4], [0, -2]], dtype=np.float16)
520
+ assert sqrtm(M).dtype == np.complex64
521
+ M = np.array([[2, 4], [0, -2]], dtype=np.float32)
522
+ assert sqrtm(M).dtype == np.complex64
523
+ M = np.array([[2, 4], [0, -2]], dtype=np.float64)
524
+ assert sqrtm(M).dtype == np.complex128
525
+ if hasattr(np, 'float128') and hasattr(np, 'complex256'):
526
+ M = np.array([[2, 4], [0, -2]], dtype=np.float128)
527
+ assert sqrtm(M).dtype == np.complex128
528
+
529
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
530
+ def test_data_size_preservation_comp_in_comp_out(self):
531
+ M = np.array([[2j, 4], [0, -2j]], dtype=np.complex64)
532
+ assert sqrtm(M).dtype == np.complex64
533
+ M = np.array([[2j, 4], [0, -2j]], dtype=np.complex128)
534
+ assert sqrtm(M).dtype == np.complex128
535
+ if hasattr(np, 'complex256'):
536
+ M = np.array([[2j, 4], [0, -2j]], dtype=np.complex256)
537
+ assert sqrtm(M).dtype == np.complex128
538
+
539
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
540
+ def test_empty(self, dt):
541
+ a = np.empty((0, 0), dtype=dt)
542
+ s = sqrtm(a)
543
+ a0 = np.eye(2, dtype=dt)
544
+ s0 = sqrtm(a0)
545
+
546
+ assert s.shape == (0, 0)
547
+ assert s.dtype == s0.dtype
548
+
549
+ def test_cf_noncontig_nd_inputs(self):
550
+ # Check that non-contiguous arrays are handled correctly.
551
+ # Generate an L, U pair for invertible random matrix.
552
+ rng = np.random.default_rng(1738151906092737)
553
+ n = 13
554
+ A = rng.uniform(size=(3, 2*n, 2*n))
555
+ L, U = np.tril(A, k=-1) + np.eye(2*n), np.triu(A)
556
+ A = L @ U
557
+ # Create strided views of 3D array.
558
+ A_noncontig_c = A[:, ::2, ::2]
559
+ A_noncontig_f = np.asfortranarray(A)[:, 1::2, 1::2]
560
+ assert_allclose(sqrtm(A[:, ::2, ::2]), sqrtm(A_noncontig_c))
561
+ assert_allclose(sqrtm(A[:, 1::2, 1::2]), sqrtm(A_noncontig_f))
562
+
563
+ def test_empty_sizes(self):
564
+ A = np.empty(shape=[4, 0, 5, 5], dtype=float)
565
+ assert_array_equal(sqrtm(A), A)
566
+
567
+ def test_negative_strides(self):
568
+ rng = np.random.default_rng(1738151906092738)
569
+ A = rng.uniform(size=(3, 5, 5))
570
+ A_negneg_orig = A[:, ::-1, ::-1]
571
+ A_negneg_copy = A[:, ::-1, ::-1].copy()
572
+ assert_allclose(sqrtm(A_negneg_orig), sqrtm(A_negneg_copy))
573
+
574
+ A_posneg_orig = A[:, :, ::-1]
575
+ A_posneg_copy = A[:, :, ::-1].copy()
576
+ assert_allclose(sqrtm(A_posneg_orig), sqrtm(A_posneg_copy))
577
+
578
+ A_negpos_orig = A[:, ::-1, :]
579
+ A_negpos_copy = A[:, ::-1, :].copy()
580
+ assert_allclose(sqrtm(A_negpos_orig), sqrtm(A_negpos_copy))
581
+
582
+ @pytest.mark.parametrize('dtyp', [np.float32, np.float64,
583
+ np.complex64, np.complex128])
584
+ def test_gh24508(self, dtyp):
585
+ # Check that sqrtm raises a warning when the input is singular
586
+ # And for this example, the top row is filled with infs.
587
+ a = np.array([[0, 2, 2], [0, 0, 0], [0, 0, 0]], dtype=dtyp)
588
+ with pytest.warns(LinAlgWarning, match="Matrix is singular."):
589
+ res = sqrtm(a)
590
+ assert np.isinf(res[0, 1:]).all()
591
+
592
+
593
+ class TestFractionalMatrixPower:
594
+ def test_round_trip_random_complex(self):
595
+ rng = np.random.default_rng(1234)
596
+ for p in range(1, 5):
597
+ for n in range(1, 5):
598
+ M_unscaled = (rng.standard_normal((n, n)) +
599
+ 1j * rng.standard_normal((n, n)))
600
+ for scale in np.logspace(-4, 4, 9):
601
+ M = M_unscaled * scale
602
+ M_root = fractional_matrix_power(M, 1/p)
603
+ M_round_trip = np.linalg.matrix_power(M_root, p)
604
+ assert_allclose(M_round_trip, M)
605
+
606
+ def test_round_trip_random_float(self):
607
+ # This test is more annoying because it can hit the branch cut;
608
+ # this happens when the matrix has an eigenvalue
609
+ # with no imaginary component and with a real negative component,
610
+ # and it means that the principal branch does not exist.
611
+ rng = np.random.default_rng(1234)
612
+ for p in range(1, 5):
613
+ for n in range(1, 5):
614
+ M_unscaled = rng.standard_normal((n, n))
615
+ for scale in np.logspace(-4, 4, 9):
616
+ M = M_unscaled * scale
617
+ M_root = fractional_matrix_power(M, 1/p)
618
+ M_round_trip = np.linalg.matrix_power(M_root, p)
619
+ assert_allclose(M_round_trip, M)
620
+
621
+ def test_larger_abs_fractional_matrix_powers(self):
622
+ rng = np.random.default_rng(1234)
623
+ for n in (2, 3, 5):
624
+ for i in range(10):
625
+ M = rng.standard_normal((n, n)) + 1j * rng.standard_normal((n, n))
626
+ M_one_fifth = fractional_matrix_power(M, 0.2)
627
+ # Test the round trip.
628
+ M_round_trip = np.linalg.matrix_power(M_one_fifth, 5)
629
+ assert_allclose(M, M_round_trip)
630
+ # Test a large abs fractional power.
631
+ X = fractional_matrix_power(M, -5.4)
632
+ Y = np.linalg.matrix_power(M_one_fifth, -27)
633
+ assert_allclose(X, Y)
634
+ # Test another large abs fractional power.
635
+ X = fractional_matrix_power(M, 3.8)
636
+ Y = np.linalg.matrix_power(M_one_fifth, 19)
637
+ assert_allclose(X, Y)
638
+
639
+ def test_random_matrices_and_powers(self):
640
+ # Each independent iteration of this fuzz test picks random parameters.
641
+ # It tries to hit some edge cases.
642
+ rng = np.random.default_rng(1726500458620605)
643
+ nsamples = 20
644
+ for i in range(nsamples):
645
+ # Sample a matrix size and a random real power.
646
+ n = rng.integers(1, 5)
647
+ p = rng.random()
648
+
649
+ # Sample a random real or complex matrix.
650
+ matrix_scale = np.exp(rng.integers(-4, 5))
651
+ A = rng.random(size=[n, n])
652
+ if [True, False][rng.choice(2)]:
653
+ A = A + 1j * rng.random(size=[n, n])
654
+ A = A * matrix_scale
655
+
656
+ # Check a couple of analytically equivalent ways
657
+ # to compute the fractional matrix power.
658
+ # These can be compared because they both use the principal branch.
659
+ A_power = fractional_matrix_power(A, p)
660
+ A_logm = logm(A)
661
+ A_power_expm_logm = expm(A_logm * p)
662
+ assert_allclose(A_power, A_power_expm_logm)
663
+
664
+ def test_al_mohy_higham_2012_experiment_1(self):
665
+ # Fractional powers of a tricky upper triangular matrix.
666
+ A = _get_al_mohy_higham_2012_experiment_1()
667
+
668
+ # Test remainder matrix power.
669
+ A_funm_sqrt = funm(A, np.sqrt)
670
+ A_sqrtm = sqrtm(A)
671
+ A_rem_power = _matfuncs_inv_ssq._remainder_matrix_power(A, 0.5)
672
+ A_power = fractional_matrix_power(A, 0.5)
673
+ assert_allclose(A_rem_power, A_power, rtol=1e-11)
674
+ assert_allclose(A_sqrtm, A_power)
675
+ assert_allclose(A_sqrtm, A_funm_sqrt)
676
+
677
+ # Test more fractional powers.
678
+ for p in (1/2, 5/3):
679
+ A_power = fractional_matrix_power(A, p)
680
+ A_round_trip = fractional_matrix_power(A_power, 1/p)
681
+ assert_allclose(A_round_trip, A, rtol=1e-2)
682
+ assert_allclose(np.tril(A_round_trip, 1), np.tril(A, 1))
683
+
684
+ def test_briggs_helper_function(self):
685
+ rng = np.random.default_rng(1234)
686
+ for a in rng.standard_normal(10) + 1j * rng.standard_normal(10):
687
+ for k in range(5):
688
+ x_observed = _matfuncs_inv_ssq._briggs_helper_function(a, k)
689
+ x_expected = a ** np.exp2(-k) - 1
690
+ assert_allclose(x_observed, x_expected)
691
+
692
+ def test_type_preservation_and_conversion(self):
693
+ # The fractional_matrix_power matrix function should preserve
694
+ # the type of a matrix whose eigenvalues
695
+ # are positive with zero imaginary part.
696
+ # Test this preservation for variously structured matrices.
697
+ complex_dtype_chars = ('F', 'D', 'G')
698
+ for matrix_as_list in (
699
+ [[1, 0], [0, 1]],
700
+ [[1, 0], [1, 1]],
701
+ [[2, 1], [1, 1]],
702
+ [[2, 3], [1, 2]]):
703
+
704
+ # check that the spectrum has the expected properties
705
+ W = scipy.linalg.eigvals(matrix_as_list)
706
+ assert_(not any(w.imag or w.real < 0 for w in W))
707
+
708
+ # Check various positive and negative powers
709
+ # with absolute values bigger and smaller than 1.
710
+ for p in (-2.4, -0.9, 0.2, 3.3):
711
+
712
+ # check float type preservation
713
+ A = np.array(matrix_as_list, dtype=float)
714
+ A_power = fractional_matrix_power(A, p)
715
+ assert_(A_power.dtype.char not in complex_dtype_chars)
716
+
717
+ # check complex type preservation
718
+ A = np.array(matrix_as_list, dtype=complex)
719
+ A_power = fractional_matrix_power(A, p)
720
+ assert_(A_power.dtype.char in complex_dtype_chars)
721
+
722
+ # check float->complex for the matrix negation
723
+ A = -np.array(matrix_as_list, dtype=float)
724
+ A_power = fractional_matrix_power(A, p)
725
+ assert_(A_power.dtype.char in complex_dtype_chars)
726
+
727
+ def test_type_conversion_mixed_sign_or_complex_spectrum(self):
728
+ complex_dtype_chars = ('F', 'D', 'G')
729
+ for matrix_as_list in (
730
+ [[1, 0], [0, -1]],
731
+ [[0, 1], [1, 0]],
732
+ [[0, 1, 0], [0, 0, 1], [1, 0, 0]]):
733
+
734
+ # check that the spectrum has the expected properties
735
+ W = scipy.linalg.eigvals(matrix_as_list)
736
+ assert_(any(w.imag or w.real < 0 for w in W))
737
+
738
+ # Check various positive and negative powers
739
+ # with absolute values bigger and smaller than 1.
740
+ for p in (-2.4, -0.9, 0.2, 3.3):
741
+
742
+ # check complex->complex
743
+ A = np.array(matrix_as_list, dtype=complex)
744
+ A_power = fractional_matrix_power(A, p)
745
+ assert_(A_power.dtype.char in complex_dtype_chars)
746
+
747
+ # check float->complex
748
+ A = np.array(matrix_as_list, dtype=float)
749
+ A_power = fractional_matrix_power(A, p)
750
+ assert_(A_power.dtype.char in complex_dtype_chars)
751
+
752
+ @pytest.mark.xfail(reason='Too unstable across LAPACKs.')
753
+ def test_singular(self):
754
+ # Negative fractional powers do not work with singular matrices.
755
+ for matrix_as_list in (
756
+ [[0, 0], [0, 0]],
757
+ [[1, 1], [1, 1]],
758
+ [[1, 2], [3, 6]],
759
+ [[0, 0, 0], [0, 1, 1], [0, -1, 1]]):
760
+
761
+ # Check fractional powers both for float and for complex types.
762
+ for newtype in (float, complex):
763
+ A = np.array(matrix_as_list, dtype=newtype)
764
+ for p in (-0.7, -0.9, -2.4, -1.3):
765
+ A_power = fractional_matrix_power(A, p)
766
+ assert_(np.isnan(A_power).all())
767
+ for p in (0.2, 1.43):
768
+ A_power = fractional_matrix_power(A, p)
769
+ A_round_trip = fractional_matrix_power(A_power, 1/p)
770
+ assert_allclose(A_round_trip, A)
771
+
772
+ def test_opposite_sign_complex_eigenvalues(self):
773
+ M = [[2j, 4], [0, -2j]]
774
+ R = [[1+1j, 2], [0, 1-1j]]
775
+ assert_allclose(np.dot(R, R), M, atol=1e-14)
776
+ assert_allclose(fractional_matrix_power(M, 0.5), R, atol=1e-14)
777
+
778
+
779
+ class TestExpM:
780
+ def test_zero(self):
781
+ a = array([[0.,0],[0,0]])
782
+ assert_array_almost_equal(expm(a),[[1,0],[0,1]])
783
+
784
+ def test_single_elt(self):
785
+ elt = expm(1)
786
+ assert_allclose(elt, np.array([[np.e]]))
787
+
788
+ @pytest.mark.parametrize('func', [expm, cosm, sinm, tanm, coshm, sinhm, tanhm])
789
+ @pytest.mark.parametrize('dt',[int, float, np.float32, complex, np.complex64])
790
+ @pytest.mark.parametrize('shape', [(0, 0), (1, 1)])
791
+ def test_small_empty_matrix_input(self, func, dt, shape):
792
+ # regression test for gh-11082 / gh-20372 - test behavior of expm
793
+ # and related functions for small and zero-sized arrays.
794
+ A = np.zeros(shape, dtype=dt)
795
+ A0 = np.zeros((10, 10), dtype=dt)
796
+ result = func(A)
797
+ result0 = func(A0)
798
+ assert result.shape == shape
799
+ assert result.dtype == result0.dtype
800
+
801
+ def test_2x2_input(self):
802
+ E = np.e
803
+ a = array([[1, 4], [1, 1]])
804
+ aa = (E**4 + 1)/(2*E)
805
+ bb = (E**4 - 1)/E
806
+ assert_allclose(expm(a), array([[aa, bb], [bb/4, aa]]))
807
+ assert expm(a.astype(np.complex64)).dtype.char == 'F'
808
+ assert expm(a.astype(np.float32)).dtype.char == 'f'
809
+
810
+ def test_nx2x2_input(self):
811
+ E = np.e
812
+ # These are integer matrices with integer eigenvalues
813
+ a = np.array([[[1, 4], [1, 1]],
814
+ [[1, 3], [1, -1]],
815
+ [[1, 3], [4, 5]],
816
+ [[1, 3], [5, 3]],
817
+ [[4, 5], [-3, -4]]], order='F')
818
+ # Exact results are computed symbolically
819
+ a_res = np.array([
820
+ [[(E**4+1)/(2*E), (E**4-1)/E],
821
+ [(E**4-1)/4/E, (E**4+1)/(2*E)]],
822
+ [[1/(4*E**2)+(3*E**2)/4, (3*E**2)/4-3/(4*E**2)],
823
+ [E**2/4-1/(4*E**2), 3/(4*E**2)+E**2/4]],
824
+ [[3/(4*E)+E**7/4, -3/(8*E)+(3*E**7)/8],
825
+ [-1/(2*E)+E**7/2, 1/(4*E)+(3*E**7)/4]],
826
+ [[5/(8*E**2)+(3*E**6)/8, -3/(8*E**2)+(3*E**6)/8],
827
+ [-5/(8*E**2)+(5*E**6)/8, 3/(8*E**2)+(5*E**6)/8]],
828
+ [[-3/(2*E)+(5*E)/2, -5/(2*E)+(5*E)/2],
829
+ [3/(2*E)-(3*E)/2, 5/(2*E)-(3*E)/2]]
830
+ ])
831
+ assert_allclose(expm(a), a_res)
832
+
833
+ def test_readonly(self):
834
+ n = 7
835
+ a = np.ones((n, n))
836
+ a.flags.writeable = False
837
+ expm(a)
838
+
839
+ @pytest.mark.fail_slow(5)
840
+ def test_gh18086(self):
841
+ A = np.zeros((400, 400), dtype=float)
842
+ rng = np.random.default_rng(100)
843
+ i = rng.integers(0, 399, 500)
844
+ j = rng.integers(0, 399, 500)
845
+ A[i, j] = rng.random(500)
846
+ # Check that result is accurate
847
+ first_res = expm(A)
848
+ np.testing.assert_array_almost_equal(logm(first_res), A)
849
+ # Check that result is consistent
850
+ for i in range(5):
851
+ next_res = expm(A)
852
+ np.testing.assert_array_almost_equal(first_res, next_res)
853
+
854
+ @pytest.mark.parametrize('dt', [np.float32, np.float64,
855
+ np.complex64, np.complex128])
856
+ def test_gh25924(self, dt):
857
+ # The scaling exponent of a slice that needed scaling and squaring
858
+ # leaked into the following slices that did not, squaring their
859
+ # unscaled results and returning expm(2**s * A) instead of expm(A).
860
+ rng = np.random.default_rng(1234)
861
+ n, batch = 6, 4
862
+ A = rng.standard_normal((batch, n, n))
863
+ if np.issubdtype(dt, np.complexfloating):
864
+ A = A + 1j*rng.standard_normal((batch, n, n))
865
+ A = A.astype(dt)
866
+ # First slice needs scaling and squaring, the remaining ones do not.
867
+ A[0] *= 8
868
+ A[1:] /= np.abs(A[1:]).sum(axis=1).max(axis=-1)[:, None, None]
869
+
870
+ one_at_a_time = np.stack([expm(x) for x in A])
871
+ assert_allclose(expm(A), one_at_a_time,
872
+ rtol=10*np.finfo(dt).eps, atol=0)
873
+
874
+
875
+ class TestExpmFrechet:
876
+
877
+ def test_expm_frechet(self):
878
+ # a test of the basic functionality
879
+ M = np.array([
880
+ [1, 2, 3, 4],
881
+ [5, 6, 7, 8],
882
+ [0, 0, 1, 2],
883
+ [0, 0, 5, 6],
884
+ ], dtype=float)
885
+ A = np.array([
886
+ [1, 2],
887
+ [5, 6],
888
+ ], dtype=float)
889
+ E = np.array([
890
+ [3, 4],
891
+ [7, 8],
892
+ ], dtype=float)
893
+ expected_expm = scipy.linalg.expm(A)
894
+ expected_frechet = scipy.linalg.expm(M)[:2, 2:]
895
+ for kwargs in ({}, {'method':'SPS'}, {'method':'blockEnlarge'}):
896
+ observed_expm, observed_frechet = expm_frechet(A, E, **kwargs)
897
+ assert_allclose(expected_expm, observed_expm)
898
+ assert_allclose(expected_frechet, observed_frechet)
899
+
900
+ def test_small_norm_expm_frechet(self):
901
+ # methodically test matrices with a range of norms, for better coverage
902
+ M_original = np.array([
903
+ [1, 2, 3, 4],
904
+ [5, 6, 7, 8],
905
+ [0, 0, 1, 2],
906
+ [0, 0, 5, 6],
907
+ ], dtype=float)
908
+ A_original = np.array([
909
+ [1, 2],
910
+ [5, 6],
911
+ ], dtype=float)
912
+ E_original = np.array([
913
+ [3, 4],
914
+ [7, 8],
915
+ ], dtype=float)
916
+ A_original_norm_1 = scipy.linalg.norm(A_original, 1)
917
+ selected_m_list = [1, 3, 5, 7, 9, 11, 13, 15]
918
+ m_neighbor_pairs = zip(selected_m_list[:-1], selected_m_list[1:])
919
+ for ma, mb in m_neighbor_pairs:
920
+ ell_a = scipy.linalg._expm_frechet.ell_table_61[ma]
921
+ ell_b = scipy.linalg._expm_frechet.ell_table_61[mb]
922
+ target_norm_1 = 0.5 * (ell_a + ell_b)
923
+ scale = target_norm_1 / A_original_norm_1
924
+ M = scale * M_original
925
+ A = scale * A_original
926
+ E = scale * E_original
927
+ expected_expm = scipy.linalg.expm(A)
928
+ expected_frechet = scipy.linalg.expm(M)[:2, 2:]
929
+ observed_expm, observed_frechet = expm_frechet(A, E)
930
+ assert_allclose(expected_expm, observed_expm)
931
+ assert_allclose(expected_frechet, observed_frechet)
932
+
933
+ def test_fuzz(self):
934
+ rng = np.random.default_rng(1726500908359153)
935
+ # try a bunch of crazy inputs
936
+ rfuncs = (
937
+ rng.uniform,
938
+ rng.normal,
939
+ rng.standard_cauchy,
940
+ rng.exponential)
941
+ ntests = 100
942
+ for i in range(ntests):
943
+ rfunc = rfuncs[rng.choice(4)]
944
+ target_norm_1 = rng.exponential()
945
+ n = rng.integers(2, 16)
946
+ A_original = rfunc(size=(n,n))
947
+ E_original = rfunc(size=(n,n))
948
+ A_original_norm_1 = scipy.linalg.norm(A_original, 1)
949
+ scale = target_norm_1 / A_original_norm_1
950
+ A = scale * A_original
951
+ E = scale * E_original
952
+ M = np.vstack([
953
+ np.hstack([A, E]),
954
+ np.hstack([np.zeros_like(A), A])])
955
+ expected_expm = scipy.linalg.expm(A)
956
+ expected_frechet = scipy.linalg.expm(M)[:n, n:]
957
+ observed_expm, observed_frechet = expm_frechet(A, E)
958
+ assert_allclose(expected_expm, observed_expm, atol=5e-8)
959
+ assert_allclose(expected_frechet, observed_frechet, atol=1e-7)
960
+
961
+ def test_problematic_matrix(self):
962
+ # this test case uncovered a bug which has since been fixed
963
+ A = np.array([
964
+ [1.50591997, 1.93537998],
965
+ [0.41203263, 0.23443516],
966
+ ], dtype=float)
967
+ E = np.array([
968
+ [1.87864034, 2.07055038],
969
+ [1.34102727, 0.67341123],
970
+ ], dtype=float)
971
+ scipy.linalg.norm(A, 1)
972
+ sps_expm, sps_frechet = expm_frechet(
973
+ A, E, method='SPS')
974
+ blockEnlarge_expm, blockEnlarge_frechet = expm_frechet(
975
+ A, E, method='blockEnlarge')
976
+ assert_allclose(sps_expm, blockEnlarge_expm)
977
+ assert_allclose(sps_frechet, blockEnlarge_frechet)
978
+
979
+ @pytest.mark.slow
980
+ @pytest.mark.skip(reason='this test is deliberately slow')
981
+ def test_medium_matrix(self):
982
+ # profile this to see the speed difference
983
+ n = 1000
984
+ rng = np.random.default_rng(1234)
985
+ A = rng.exponential(size=(n, n))
986
+ E = rng.exponential(size=(n, n))
987
+ sps_expm, sps_frechet = expm_frechet(
988
+ A, E, method='SPS')
989
+ blockEnlarge_expm, blockEnlarge_frechet = expm_frechet(
990
+ A, E, method='blockEnlarge')
991
+ assert_allclose(sps_expm, blockEnlarge_expm)
992
+ assert_allclose(sps_frechet, blockEnlarge_frechet)
993
+
994
+
995
+ def _help_expm_cond_search(A, A_norm, X, X_norm, eps, p):
996
+ p = np.reshape(p, A.shape)
997
+ p_norm = norm(p)
998
+ perturbation = eps * p * (A_norm / p_norm)
999
+ X_prime = expm(A + perturbation)
1000
+ scaled_relative_error = norm(X_prime - X) / (X_norm * eps)
1001
+ return -scaled_relative_error
1002
+
1003
+
1004
+ def _normalized_like(A, B):
1005
+ return A * (scipy.linalg.norm(B) / scipy.linalg.norm(A))
1006
+
1007
+
1008
+ def _relative_error(f, A, perturbation):
1009
+ X = f(A)
1010
+ X_prime = f(A + perturbation)
1011
+ return norm(X_prime - X) / norm(X)
1012
+
1013
+
1014
+ class TestExpmConditionNumber:
1015
+ def test_expm_cond_smoke(self):
1016
+ rng = np.random.default_rng(1234)
1017
+ for n in range(1, 4):
1018
+ A = rng.standard_normal((n, n))
1019
+ kappa = expm_cond(A)
1020
+ assert_array_less(0, kappa)
1021
+
1022
+ def test_expm_bad_condition_number(self):
1023
+ A = np.array([
1024
+ [-1.128679820, 9.614183771e4, -4.524855739e9, 2.924969411e14],
1025
+ [0, -1.201010529, 9.634696872e4, -4.681048289e9],
1026
+ [0, 0, -1.132893222, 9.532491830e4],
1027
+ [0, 0, 0, -1.179475332],
1028
+ ])
1029
+ kappa = expm_cond(A)
1030
+ assert_array_less(1e36, kappa)
1031
+
1032
+ def test_univariate(self):
1033
+ rng = np.random.default_rng(1234)
1034
+ for x in np.linspace(-5, 5, num=11):
1035
+ A = np.array([[x]])
1036
+ assert_allclose(expm_cond(A), abs(x))
1037
+ for x in np.logspace(-2, 2, num=11):
1038
+ A = np.array([[x]])
1039
+ assert_allclose(expm_cond(A), abs(x))
1040
+ for i in range(10):
1041
+ A = rng.standard_normal((1, 1))
1042
+ assert_allclose(expm_cond(A), np.absolute(A)[0, 0])
1043
+
1044
+ @pytest.mark.slow
1045
+ def test_expm_cond_fuzz(self):
1046
+ rng = np.random.RandomState(12345)
1047
+ eps = 1e-5
1048
+ nsamples = 10
1049
+ for i in range(nsamples):
1050
+ n = rng.randint(2, 5)
1051
+ A = rng.randn(n, n)
1052
+ A_norm = scipy.linalg.norm(A)
1053
+ X = expm(A)
1054
+ X_norm = scipy.linalg.norm(X)
1055
+ kappa = expm_cond(A)
1056
+
1057
+ # Look for the small perturbation that gives the greatest
1058
+ # relative error.
1059
+ f = functools.partial(_help_expm_cond_search,
1060
+ A, A_norm, X, X_norm, eps)
1061
+ guess = np.ones(n*n)
1062
+ out = minimize(f, guess, method='L-BFGS-B')
1063
+ xopt = out.x
1064
+ yopt = f(xopt)
1065
+ p_best = eps * _normalized_like(np.reshape(xopt, A.shape), A)
1066
+ p_best_relerr = _relative_error(expm, A, p_best)
1067
+ assert_allclose(p_best_relerr, -yopt * eps)
1068
+
1069
+ # Check that the identified perturbation indeed gives greater
1070
+ # relative error than random perturbations with similar norms.
1071
+ for j in range(5):
1072
+ p_rand = eps * _normalized_like(rng.randn(*A.shape), A)
1073
+ assert_allclose(norm(p_best), norm(p_rand))
1074
+ p_rand_relerr = _relative_error(expm, A, p_rand)
1075
+ assert_array_less(p_rand_relerr, p_best_relerr)
1076
+
1077
+ # The greatest relative error should not be much greater than
1078
+ # eps times the condition number kappa.
1079
+ # In the limit as eps approaches zero it should never be greater.
1080
+ assert_array_less(p_best_relerr, (1 + 2*eps) * eps * kappa)
1081
+
1082
+
1083
+ class TestKhatriRao:
1084
+
1085
+ def test_basic(self):
1086
+ a = khatri_rao(array([[1, 2], [3, 4]]),
1087
+ array([[5, 6], [7, 8]]))
1088
+
1089
+ assert_array_equal(a, array([[5, 12],
1090
+ [7, 16],
1091
+ [15, 24],
1092
+ [21, 32]]))
1093
+
1094
+ b = khatri_rao(np.empty([2, 2]), np.empty([2, 2]))
1095
+ assert_array_equal(b.shape, (4, 2))
1096
+
1097
+ def test_number_of_columns_equality(self):
1098
+ with pytest.raises(ValueError):
1099
+ a = array([[1, 2, 3],
1100
+ [4, 5, 6]])
1101
+ b = array([[1, 2],
1102
+ [3, 4]])
1103
+ khatri_rao(a, b)
1104
+
1105
+ def test_to_assure_2d_array(self):
1106
+ with pytest.raises(ValueError):
1107
+ # both arrays are 1-D
1108
+ a = array([1, 2, 3])
1109
+ b = array([4, 5, 6])
1110
+ khatri_rao(a, b)
1111
+
1112
+ with pytest.raises(ValueError):
1113
+ # first array is 1-D
1114
+ a = array([1, 2, 3])
1115
+ b = array([
1116
+ [1, 2, 3],
1117
+ [4, 5, 6]
1118
+ ])
1119
+ khatri_rao(a, b)
1120
+
1121
+ with pytest.raises(ValueError):
1122
+ # second array is 1-D
1123
+ a = array([
1124
+ [1, 2, 3],
1125
+ [7, 8, 9]
1126
+ ])
1127
+ b = array([4, 5, 6])
1128
+ khatri_rao(a, b)
1129
+
1130
+ def test_equality_of_two_equations(self):
1131
+ a = array([[1, 2], [3, 4]])
1132
+ b = array([[5, 6], [7, 8]])
1133
+
1134
+ res1 = khatri_rao(a, b)
1135
+ res2 = np.vstack([np.kron(a[:, k], b[:, k])
1136
+ for k in range(b.shape[1])]).T
1137
+
1138
+ assert_array_equal(res1, res2)
1139
+
1140
+ def test_empty(self):
1141
+ a = np.empty((0, 2))
1142
+ b = np.empty((3, 2))
1143
+ res = khatri_rao(a, b)
1144
+ assert_allclose(res, np.empty((0, 2)))
1145
+
1146
+ a = np.empty((3, 0))
1147
+ b = np.empty((5, 0))
1148
+ res = khatri_rao(a, b)
1149
+ assert_allclose(res, np.empty((15, 0)))
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test functions for linalg.matmul_toeplitz function
2
+ """
3
+
4
+ import numpy as np
5
+ from scipy.linalg import toeplitz, matmul_toeplitz
6
+
7
+ from pytest import raises as assert_raises
8
+ from numpy.testing import assert_allclose
9
+
10
+
11
+ class TestMatmulToeplitz:
12
+
13
+ def setup_method(self):
14
+ self.rng = np.random.RandomState(42)
15
+ self.tolerance = 1.5e-13
16
+
17
+ def test_real(self):
18
+ cases = []
19
+
20
+ n = 1
21
+ c = self.rng.normal(size=n)
22
+ r = self.rng.normal(size=n)
23
+ x = self.rng.normal(size=(n, 1))
24
+ cases.append((x, c, r, False))
25
+
26
+ n = 2
27
+ c = self.rng.normal(size=n)
28
+ r = self.rng.normal(size=n)
29
+ x = self.rng.normal(size=(n, 1))
30
+ cases.append((x, c, r, False))
31
+
32
+ n = 101
33
+ c = self.rng.normal(size=n)
34
+ r = self.rng.normal(size=n)
35
+ x = self.rng.normal(size=(n, 1))
36
+ cases.append((x, c, r, True))
37
+
38
+ n = 1000
39
+ c = self.rng.normal(size=n)
40
+ r = self.rng.normal(size=n)
41
+ x = self.rng.normal(size=(n, 1))
42
+ cases.append((x, c, r, False))
43
+
44
+ n = 100
45
+ c = self.rng.normal(size=n)
46
+ r = self.rng.normal(size=n)
47
+ x = self.rng.normal(size=(n, self.rng.randint(1, 10)))
48
+ cases.append((x, c, r, False))
49
+
50
+ n = 100
51
+ c = self.rng.normal(size=(n, 1))
52
+ r = self.rng.normal(size=(n, 1))
53
+ x = self.rng.normal(size=(n, self.rng.randint(1, 10)))
54
+ cases.append((x, c, r, True))
55
+
56
+ n = 100
57
+ c = self.rng.normal(size=(n, 1))
58
+ r = None
59
+ x = self.rng.normal(size=(n, self.rng.randint(1, 10)))
60
+ cases.append((x, c, r, True, -1))
61
+
62
+ n = 100
63
+ c = self.rng.normal(size=(n, 1))
64
+ r = None
65
+ x = self.rng.normal(size=n)
66
+ cases.append((x, c, r, False))
67
+
68
+ n = 101
69
+ c = self.rng.normal(size=n)
70
+ r = self.rng.normal(size=n-27)
71
+ x = self.rng.normal(size=(n-27, 1))
72
+ cases.append((x, c, r, True))
73
+
74
+ n = 100
75
+ c = self.rng.normal(size=n)
76
+ r = self.rng.normal(size=n//4)
77
+ x = self.rng.normal(size=(n//4, self.rng.randint(1, 10)))
78
+ cases.append((x, c, r, True))
79
+
80
+ [self.do(*i) for i in cases]
81
+
82
+ def test_complex(self):
83
+ n = 127
84
+ c = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j
85
+ r = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j
86
+ x = self.rng.normal(size=(n, 3)) + self.rng.normal(size=(n, 3))*1j
87
+ self.do(x, c, r, False)
88
+
89
+ n = 100
90
+ c = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j
91
+ r = self.rng.normal(size=(n//2, 1)) +\
92
+ self.rng.normal(size=(n//2, 1))*1j
93
+ x = self.rng.normal(size=(n//2, 3)) +\
94
+ self.rng.normal(size=(n//2, 3))*1j
95
+ self.do(x, c, r, False)
96
+
97
+ def test_empty(self):
98
+ c = []
99
+ r = []
100
+ x = []
101
+ self.do(x, c, r, False)
102
+
103
+ x = np.empty((0, 0))
104
+ self.do(x, c, r, False)
105
+
106
+ def test_exceptions(self):
107
+
108
+ n = 100
109
+ c = self.rng.normal(size=n)
110
+ r = self.rng.normal(size=2*n)
111
+ x = self.rng.normal(size=n)
112
+ assert_raises(ValueError, matmul_toeplitz, (c, r), x, True)
113
+
114
+ n = 100
115
+ c = self.rng.normal(size=n)
116
+ r = self.rng.normal(size=n)
117
+ x = self.rng.normal(size=n-1)
118
+ assert_raises(ValueError, matmul_toeplitz, (c, r), x, True)
119
+
120
+ n = 100
121
+ c = self.rng.normal(size=n)
122
+ r = self.rng.normal(size=n//2)
123
+ x = self.rng.normal(size=n//2-1)
124
+ assert_raises(ValueError, matmul_toeplitz, (c, r), x, True)
125
+
126
+ # For toeplitz matrices, matmul_toeplitz() should be equivalent to @.
127
+ def do(self, x, c, r=None, check_finite=False, workers=None):
128
+ c = np.ravel(c)
129
+ if r is None:
130
+ actual = matmul_toeplitz(c, x, check_finite, workers)
131
+ else:
132
+ r = np.ravel(r)
133
+ actual = matmul_toeplitz((c, r), x, check_finite)
134
+ desired = toeplitz(c, r) @ x
135
+ assert_allclose(actual, desired,
136
+ rtol=self.tolerance, atol=self.tolerance)
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_procrustes.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import product, permutations
2
+
3
+ import numpy as np
4
+ import pytest
5
+ from numpy.testing import assert_allclose
6
+ from pytest import raises as assert_raises
7
+
8
+ from scipy.linalg import orthogonal_procrustes
9
+ from scipy.sparse._sputils import matrix
10
+ from scipy._lib._array_api import make_xp_test_case, xp_assert_close
11
+ from scipy.conftest import skip_xp_invalid_arg
12
+
13
+ def _centered(A, xp):
14
+ mu = xp.mean(A, axis=0)
15
+ return A - mu, mu
16
+
17
+ @make_xp_test_case(orthogonal_procrustes)
18
+ class TestOrthogonalProcrustes:
19
+ def test_orthogonal_procrustes_ndim_too_small(self, xp):
20
+ rng = np.random.RandomState(1234)
21
+ A = xp.asarray(rng.randn(3))
22
+ B = xp.asarray(rng.randn(3))
23
+ assert_raises(ValueError, orthogonal_procrustes, A, B)
24
+
25
+ def test_orthogonal_procrustes_shape_mismatch(self, xp):
26
+ rng = np.random.RandomState(1234)
27
+ shapes = ((3, 3), (3, 4), (4, 3), (4, 4))
28
+ for a, b in permutations(shapes, 2):
29
+ A = xp.asarray(rng.randn(*a))
30
+ B = xp.asarray(rng.randn(*b))
31
+ assert_raises(ValueError, orthogonal_procrustes, A, B)
32
+
33
+ def test_orthogonal_procrustes_checkfinite_exception(self, xp):
34
+ rng = np.random.RandomState(1234)
35
+ m, n = 2, 3
36
+ A_good = rng.randn(m, n)
37
+ B_good = rng.randn(m, n)
38
+ for bad_value in np.inf, -np.inf, np.nan:
39
+ A_bad = A_good.copy()
40
+ A_bad[1, 2] = bad_value
41
+ B_bad = B_good.copy()
42
+ B_bad[1, 2] = bad_value
43
+ for A, B in ((A_good, B_bad), (A_bad, B_good), (A_bad, B_bad)):
44
+ assert_raises(ValueError, orthogonal_procrustes, xp.asarray(A),
45
+ xp.asarray(B))
46
+
47
+ def test_orthogonal_procrustes_scale_invariance(self, xp):
48
+ rng = np.random.RandomState(1234)
49
+ m, n = 4, 3
50
+ for i in range(3):
51
+ A_orig = xp.asarray(rng.randn(m, n))
52
+ B_orig = xp.asarray(rng.randn(m, n))
53
+ R_orig, s = orthogonal_procrustes(A_orig, B_orig)
54
+ for A_scale in np.square(rng.randn(3)):
55
+ for B_scale in np.square(rng.randn(3)):
56
+ R, s = orthogonal_procrustes(A_orig * xp.asarray(A_scale),
57
+ B_orig * xp.asarray(B_scale))
58
+ xp_assert_close(R, R_orig)
59
+
60
+ @skip_xp_invalid_arg()
61
+ def test_orthogonal_procrustes_array_conversion(self):
62
+ rng = np.random.RandomState(1234)
63
+ for m, n in ((6, 4), (4, 4), (4, 6)):
64
+ A_arr = rng.randn(m, n)
65
+ B_arr = rng.randn(m, n)
66
+ As = (A_arr, A_arr.tolist(), matrix(A_arr))
67
+ Bs = (B_arr, B_arr.tolist(), matrix(B_arr))
68
+ R_arr, s = orthogonal_procrustes(A_arr, B_arr)
69
+ AR_arr = A_arr.dot(R_arr)
70
+ for A, B in product(As, Bs):
71
+ R, s = orthogonal_procrustes(A, B)
72
+ AR = A_arr.dot(R)
73
+ assert_allclose(AR, AR_arr)
74
+
75
+ def test_orthogonal_procrustes(self, xp):
76
+ rng = np.random.RandomState(1234)
77
+ for m, n in ((6, 4), (4, 4), (4, 6)):
78
+ # Sample a random target matrix.
79
+ B = xp.asarray(rng.randn(m, n))
80
+ # Sample a random orthogonal matrix
81
+ # by computing eigh of a sampled symmetric matrix.
82
+ X = xp.asarray(rng.randn(n, n))
83
+ w, V = xp.linalg.eigh(X.T + X)
84
+ xp_assert_close(xp.linalg.inv(V), V.T)
85
+ # Compute a matrix with a known orthogonal transformation that gives B.
86
+ A = B @ V.T
87
+ # Check that an orthogonal transformation from A to B can be recovered.
88
+ R, s = orthogonal_procrustes(A, B)
89
+ xp_assert_close(xp.linalg.inv(R), R.T)
90
+ xp_assert_close(A @ R, B)
91
+ # Create a perturbed input matrix.
92
+ A_perturbed = A + 1e-2 * xp.asarray(rng.randn(m, n))
93
+ # Check that the orthogonal procrustes function can find an orthogonal
94
+ # transformation that is better than the orthogonal transformation
95
+ # computed from the original input matrix.
96
+ R_prime, s = orthogonal_procrustes(A_perturbed, B)
97
+ xp_assert_close(xp.linalg.inv(R_prime), R_prime.T)
98
+ # Compute the naive and optimal transformations of the perturbed input.
99
+ naive_approx = A_perturbed @ R
100
+ optim_approx = A_perturbed @ R_prime
101
+ # Compute the Frobenius norm errors of the matrix approximations.
102
+ naive_approx_error = xp.linalg.matrix_norm(naive_approx - B, ord='fro')
103
+ optim_approx_error = xp.linalg.matrix_norm(optim_approx - B, ord='fro')
104
+ # Check that the orthogonal Procrustes approximation is better.
105
+ assert xp.all(optim_approx_error < naive_approx_error)
106
+
107
+ def test_orthogonal_procrustes_exact_example(self, xp):
108
+ # Check a small application.
109
+ # It uses translation, scaling, reflection, and rotation.
110
+ #
111
+ # |
112
+ # a b |
113
+ # |
114
+ # d c | w
115
+ # |
116
+ # --------+--- x ----- z ---
117
+ # |
118
+ # | y
119
+ # |
120
+ #
121
+ A_orig = xp.asarray([[-3, 3], [-2, 3], [-2, 2], [-3, 2]], dtype=xp.float64)
122
+ B_orig = xp.asarray([[3, 2], [1, 0], [3, -2], [5, 0]], dtype=xp.float64)
123
+ A, A_mu = _centered(A_orig, xp)
124
+ B, B_mu = _centered(B_orig, xp)
125
+ R, s = orthogonal_procrustes(A, B)
126
+ scale = s / xp.linalg.matrix_norm(A)**2
127
+ B_approx = scale * A @ R + B_mu
128
+ xp_assert_close(B_approx, B_orig, atol=1e-8)
129
+
130
+ def test_orthogonal_procrustes_stretched_example(self, xp):
131
+ # Try again with a target with a stretched y axis.
132
+ A_orig = xp.asarray([[-3, 3], [-2, 3], [-2, 2], [-3, 2]], dtype=xp.float64)
133
+ B_orig = xp.asarray([[3, 40], [1, 0], [3, -40], [5, 0]], dtype=xp.float64)
134
+ A, A_mu = _centered(A_orig, xp)
135
+ B, B_mu = _centered(B_orig, xp)
136
+ R, s = orthogonal_procrustes(A, B)
137
+ scale = s / xp.linalg.matrix_norm(A)**2
138
+ B_approx = scale * A @ R + B_mu
139
+ expected = xp.asarray([[3, 21], [-18, 0], [3, -21], [24, 0]], dtype=xp.float64)
140
+ xp_assert_close(B_approx, expected, atol=1e-8)
141
+ # Check disparity symmetry.
142
+ expected_disparity = xp.asarray(0.4501246882793018, dtype=xp.float64)[()]
143
+ AB_disparity = (xp.linalg.matrix_norm(B_approx - B_orig)
144
+ / xp.linalg.matrix_norm(B))**2
145
+ xp_assert_close(AB_disparity, expected_disparity)
146
+ R, s = orthogonal_procrustes(B, A)
147
+ scale = s / xp.linalg.matrix_norm(B)**2
148
+ A_approx = scale * B @ R + A_mu
149
+ BA_disparity = (xp.linalg.matrix_norm(A_approx - A_orig)
150
+ / xp.linalg.matrix_norm(A))**2
151
+ xp_assert_close(BA_disparity, expected_disparity)
152
+
153
+ def test_orthogonal_procrustes_skbio_example(self, xp):
154
+ # This transformation is also exact.
155
+ # It uses translation, scaling, and reflection.
156
+ #
157
+ # |
158
+ # | a
159
+ # | b
160
+ # | c d
161
+ # --+---------
162
+ # |
163
+ # | w
164
+ # |
165
+ # | x
166
+ # |
167
+ # | z y
168
+ # |
169
+ #
170
+ A_orig = xp.asarray([[4, -2], [4, -4], [4, -6], [2, -6]], dtype=xp.float64)
171
+ B_orig = xp.asarray([[1, 3], [1, 2], [1, 1], [2, 1]], dtype=xp.float64)
172
+ B_standardized = xp.asarray([[-0.13363062, 0.6681531],
173
+ [-0.13363062, 0.13363062],
174
+ [-0.13363062, -0.40089186],
175
+ [0.40089186, -0.40089186]], dtype=xp.float64)
176
+ A, A_mu = _centered(A_orig, xp)
177
+ B, B_mu = _centered(B_orig, xp)
178
+ R, s = orthogonal_procrustes(A, B)
179
+ scale = s / xp.linalg.matrix_norm(A)**2
180
+ B_approx = scale * A @ R + B_mu
181
+ xp_assert_close(B_approx, B_orig)
182
+ xp_assert_close(B / xp.linalg.matrix_norm(B), B_standardized)
183
+
184
+ def test_empty(self, xp):
185
+ a = xp.empty((0, 0))
186
+ r, s = orthogonal_procrustes(a, a)
187
+ xp_assert_close(r, xp.empty((0, 0)))
188
+
189
+ a = xp.empty((0, 3))
190
+ r, s = orthogonal_procrustes(a, a)
191
+ xp_assert_close(r, xp.eye(3))
192
+
193
+ @pytest.mark.parametrize('shape', [(4, 5), (5, 5), (5, 4)])
194
+ def test_unitary(self, shape, xp):
195
+ # gh-12071 added support for unitary matrices; check that it
196
+ # works as intended.
197
+ m, n = shape
198
+ rng = np.random.default_rng(589234981235)
199
+ A = xp.asarray(rng.random(shape) + rng.random(shape) * 1j)
200
+ Q = xp.asarray(rng.random((n, n)) + rng.random((n, n)) * 1j)
201
+ Q, _ = xp.linalg.qr(Q)
202
+ B = A @ Q
203
+ R, scale = orthogonal_procrustes(A, B)
204
+ xp_assert_close(R @ xp.conj(R).T, xp.eye(n, dtype=xp.complex128), atol=1e-14)
205
+ xp_assert_close(A @ Q, B)
206
+ if shape != (4, 5): # solution is unique
207
+ xp_assert_close(R, Q)
208
+ _, s, _ = xp.linalg.svd(xp.conj(A).T @ B)
209
+ xp_assert_close(scale, xp.sum(s))
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_sketches.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for _sketches.py."""
2
+
3
+ import numpy as np
4
+ from numpy.testing import assert_, assert_equal
5
+ from scipy.linalg import clarkson_woodruff_transform
6
+ from scipy.linalg._sketches import cwt_matrix
7
+ from scipy.sparse import issparse, random_array
8
+ from scipy.sparse.linalg import norm
9
+
10
+
11
+ class TestClarksonWoodruffTransform:
12
+ """
13
+ Testing the Clarkson Woodruff Transform
14
+ """
15
+ # set seed for generating test matrices
16
+ rng = np.random.default_rng(1179103485)
17
+
18
+ # Test matrix parameters
19
+ n_rows = 2000
20
+ n_cols = 100
21
+ density = 0.1
22
+
23
+ # Sketch matrix dimensions
24
+ n_sketch_rows = 200
25
+
26
+ # Seeds to test with
27
+ seeds = [1755490010, 934377150, 1391612830, 1752708722, 2008891431,
28
+ 1302443994, 1521083269, 1501189312, 1126232505, 1533465685]
29
+
30
+ shape = (n_rows, n_cols)
31
+ A_dense = rng.random(shape)
32
+ A_csc = random_array(shape, density=density, format='csc', rng=rng)
33
+ A_csr = random_array(shape, density=density, format='csr', rng=rng)
34
+ A_coo = random_array(shape, density=density, format='coo', rng=rng)
35
+
36
+ # Collect the test matrices
37
+ test_matrices = [A_dense, A_csc, A_csr, A_coo]
38
+
39
+ # Test vector with norm ~1
40
+ x = rng.random((n_rows, 1)) / np.sqrt(n_rows)
41
+ del rng # Not deterministic in pytest-run-parallel
42
+
43
+ def test_sketch_dimensions(self):
44
+ for A in self.test_matrices:
45
+ for seed in self.seeds:
46
+ # seed to ensure backwards compatibility post SPEC7
47
+ sketch = clarkson_woodruff_transform(
48
+ A, self.n_sketch_rows, seed=seed
49
+ )
50
+ assert_(sketch.shape == (self.n_sketch_rows, self.n_cols))
51
+
52
+ def test_seed_returns_identical_transform_matrix(self):
53
+ for seed in self.seeds:
54
+ S1 = cwt_matrix(
55
+ self.n_sketch_rows, self.n_rows, rng=seed
56
+ ).toarray()
57
+ S2 = cwt_matrix(
58
+ self.n_sketch_rows, self.n_rows, rng=seed
59
+ ).toarray()
60
+ assert_equal(S1, S2)
61
+
62
+ def test_seed_returns_identically(self):
63
+ for A in self.test_matrices:
64
+ for seed in self.seeds:
65
+ sketch1 = clarkson_woodruff_transform(
66
+ A, self.n_sketch_rows, rng=seed
67
+ )
68
+ sketch2 = clarkson_woodruff_transform(
69
+ A, self.n_sketch_rows, rng=seed
70
+ )
71
+ if issparse(sketch1):
72
+ sketch1 = sketch1.toarray()
73
+ if issparse(sketch2):
74
+ sketch2 = sketch2.toarray()
75
+ assert_equal(sketch1, sketch2)
76
+
77
+ def test_sketch_preserves_frobenius_norm(self):
78
+ # Given the probabilistic nature of the sketches
79
+ # we run the test multiple times and check that
80
+ # we pass all/almost all the tries.
81
+ n_errors = 0
82
+ for A in self.test_matrices:
83
+ if issparse(A):
84
+ true_norm = norm(A)
85
+ else:
86
+ true_norm = np.linalg.norm(A)
87
+ for seed in self.seeds:
88
+ sketch = clarkson_woodruff_transform(
89
+ A, self.n_sketch_rows, rng=seed,
90
+ )
91
+ if issparse(sketch):
92
+ sketch_norm = norm(sketch)
93
+ else:
94
+ sketch_norm = np.linalg.norm(sketch)
95
+
96
+ if np.abs(true_norm - sketch_norm) > 0.1 * true_norm:
97
+ n_errors += 1
98
+ assert_(n_errors == 0)
99
+
100
+ def test_sketch_preserves_vector_norm(self):
101
+ n_errors = 0
102
+ n_sketch_rows = int(np.ceil(2. / (0.01 * 0.5**2)))
103
+ true_norm = np.linalg.norm(self.x)
104
+ for seed in self.seeds:
105
+ sketch = clarkson_woodruff_transform(
106
+ self.x, n_sketch_rows, rng=seed,
107
+ )
108
+ sketch_norm = np.linalg.norm(sketch)
109
+
110
+ if np.abs(true_norm - sketch_norm) > 0.5 * true_norm:
111
+ n_errors += 1
112
+ assert_(n_errors == 0)
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_solve_toeplitz.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test functions for linalg._solve_toeplitz module
2
+ """
3
+ import numpy as np
4
+ from scipy.linalg._solve_toeplitz import levinson
5
+ from scipy.linalg import solve, toeplitz, solve_toeplitz
6
+ from numpy.testing import assert_equal, assert_allclose
7
+
8
+ import pytest
9
+ from pytest import raises as assert_raises
10
+
11
+
12
+ def test_solve_equivalence():
13
+ # For toeplitz matrices, solve_toeplitz() should be equivalent to solve().
14
+ random = np.random.RandomState(1234)
15
+ for n in (1, 2, 3, 10):
16
+ c = random.randn(n)
17
+ if random.rand() < 0.5:
18
+ c = c + 1j * random.randn(n)
19
+ r = random.randn(n)
20
+ if random.rand() < 0.5:
21
+ r = r + 1j * random.randn(n)
22
+ y = random.randn(n)
23
+ if random.rand() < 0.5:
24
+ y = y + 1j * random.randn(n)
25
+
26
+ # Check equivalence when both the column and row are provided.
27
+ actual = solve_toeplitz((c,r), y)
28
+ desired = solve(toeplitz(c, r=r), y)
29
+ assert_allclose(actual, desired)
30
+
31
+ # Check equivalence when the column is provided but not the row.
32
+ actual = solve_toeplitz(c, b=y)
33
+ desired = solve(toeplitz(c), y)
34
+ assert_allclose(actual, desired)
35
+
36
+
37
+ def test_multiple_rhs():
38
+ random = np.random.RandomState(1234)
39
+ c = random.randn(4)
40
+ r = random.randn(4)
41
+ for offset in [0, 1j]:
42
+ for yshape in ((4,), (4, 3)):
43
+ y = random.randn(*yshape) + offset
44
+ actual = solve_toeplitz((c,r), b=y)
45
+ desired = solve(toeplitz(c, r=r), y)
46
+ assert_equal(actual.shape, yshape)
47
+ assert_equal(desired.shape, yshape)
48
+ assert_allclose(actual, desired)
49
+
50
+
51
+ def test_native_list_arguments():
52
+ c = [1,2,4,7]
53
+ r = [1,3,9,12]
54
+ y = [5,1,4,2]
55
+ actual = solve_toeplitz((c,r), y)
56
+ desired = solve(toeplitz(c, r=r), y)
57
+ assert_allclose(actual, desired)
58
+
59
+
60
+ def test_zero_diag_error():
61
+ # The Levinson-Durbin implementation fails when the diagonal is zero.
62
+ random = np.random.RandomState(1234)
63
+ n = 4
64
+ c = random.randn(n)
65
+ r = random.randn(n)
66
+ y = random.randn(n)
67
+ c[0] = 0
68
+ assert_raises(np.linalg.LinAlgError,
69
+ solve_toeplitz, (c, r), b=y)
70
+
71
+
72
+ def test_wikipedia_counterexample():
73
+ # The Levinson-Durbin implementation also fails in other cases.
74
+ # This example is from the talk page of the wikipedia article.
75
+ random = np.random.RandomState(1234)
76
+ c = [2, 2, 1]
77
+ y = random.randn(3)
78
+ assert_raises(np.linalg.LinAlgError, solve_toeplitz, c, b=y)
79
+
80
+
81
+ def test_reflection_coeffs():
82
+ # check that the partial solutions are given by the reflection
83
+ # coefficients
84
+
85
+ random = np.random.RandomState(1234)
86
+ y_d = random.randn(10)
87
+ y_z = random.randn(10) + 1j
88
+ reflection_coeffs_d = [1]
89
+ reflection_coeffs_z = [1]
90
+ for i in range(2, 10):
91
+ reflection_coeffs_d.append(solve_toeplitz(y_d[:(i-1)], b=y_d[1:i])[-1])
92
+ reflection_coeffs_z.append(solve_toeplitz(y_z[:(i-1)], b=y_z[1:i])[-1])
93
+
94
+ y_d_concat = np.concatenate((y_d[-2:0:-1], y_d[:-1]))
95
+ y_z_concat = np.concatenate((y_z[-2:0:-1].conj(), y_z[:-1]))
96
+ _, ref_d = levinson(y_d_concat, b=y_d[1:])
97
+ _, ref_z = levinson(y_z_concat, b=y_z[1:])
98
+
99
+ assert_allclose(reflection_coeffs_d, ref_d[:-1])
100
+ assert_allclose(reflection_coeffs_z, ref_z[:-1])
101
+
102
+
103
+ @pytest.mark.xfail(reason='Instability of Levinson iteration')
104
+ def test_unstable():
105
+ # this is a "Gaussian Toeplitz matrix", as mentioned in Example 2 of
106
+ # I. Gohbert, T. Kailath and V. Olshevsky "Fast Gaussian Elimination with
107
+ # Partial Pivoting for Matrices with Displacement Structure"
108
+ # Mathematics of Computation, 64, 212 (1995), pp 1557-1576
109
+ # which can be unstable for levinson recursion.
110
+
111
+ # other fast toeplitz solvers such as GKO or Burg should be better.
112
+ random = np.random.RandomState(1234)
113
+ n = 100
114
+ c = 0.9 ** (np.arange(n)**2)
115
+ y = random.randn(n)
116
+
117
+ solution1 = solve_toeplitz(c, b=y)
118
+ solution2 = solve(toeplitz(c), y)
119
+
120
+ assert_allclose(solution1, solution2)
121
+
122
+
123
+ @pytest.mark.parametrize('dt_c', [int, float, np.float32, complex, np.complex64])
124
+ @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
125
+ def test_empty(dt_c, dt_b):
126
+ c = np.array([], dtype=dt_c)
127
+ b = np.array([], dtype=dt_b)
128
+ x = solve_toeplitz(c, b)
129
+ assert x.shape == (0,)
130
+ assert x.dtype == solve_toeplitz(np.array([2, 1], dtype=dt_c),
131
+ np.ones(2, dtype=dt_b)).dtype
132
+
133
+ b = np.empty((0, 0), dtype=dt_b)
134
+ x1 = solve_toeplitz(c, b)
135
+ assert x1.shape == (0, 0)
136
+ assert x1.dtype == x.dtype
137
+
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_solvers.py ADDED
@@ -0,0 +1,862 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+
4
+ from numpy.testing import assert_array_almost_equal, assert_allclose
5
+ import pytest
6
+ from pytest import raises as assert_raises
7
+
8
+ from scipy.linalg import solve_sylvester
9
+ from scipy.linalg import solve_continuous_lyapunov, solve_discrete_lyapunov
10
+ from scipy.linalg import solve_continuous_are, solve_discrete_are
11
+ from scipy.linalg import block_diag, solve, LinAlgError
12
+ from scipy.sparse._sputils import matrix
13
+ from scipy.conftest import skip_xp_invalid_arg
14
+
15
+
16
+ # dtypes for testing size-0 case following precedent set in gh-20295
17
+ dtypes = [int, float, np.float32, complex, np.complex64]
18
+
19
+
20
+ def _load_data(name):
21
+ """
22
+ Load npz data file under data/
23
+ Returns a copy of the data, rather than keeping the npz file open.
24
+ """
25
+ filename = os.path.join(os.path.abspath(os.path.dirname(__file__)),
26
+ 'data', name)
27
+ with np.load(filename) as f:
28
+ return dict(f.items())
29
+
30
+
31
+ class TestSolveLyapunov:
32
+
33
+ cases = [
34
+ # empty case
35
+ (np.empty((0, 0)),
36
+ np.empty((0, 0))),
37
+ (np.array([[1, 2], [3, 4]]),
38
+ np.array([[9, 10], [11, 12]])),
39
+ # a, q all complex.
40
+ (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
41
+ np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
42
+ # a real; q complex.
43
+ (np.array([[1.0, 2.0], [3.0, 5.0]]),
44
+ np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
45
+ # a complex; q real.
46
+ (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
47
+ np.array([[2.0, 2.0], [-1.0, 2.0]])),
48
+ # An example from Kitagawa, 1977
49
+ (np.array([[3, 9, 5, 1, 4], [1, 2, 3, 8, 4], [4, 6, 6, 6, 3],
50
+ [1, 5, 2, 0, 7], [5, 3, 3, 1, 5]]),
51
+ np.array([[2, 4, 1, 0, 1], [4, 1, 0, 2, 0], [1, 0, 3, 0, 3],
52
+ [0, 2, 0, 1, 0], [1, 0, 3, 0, 4]])),
53
+ # Companion matrix example. a complex; q real; a.shape[0] = 11
54
+ (np.array([[0.100+0.j, 0.091+0.j, 0.082+0.j, 0.073+0.j, 0.064+0.j,
55
+ 0.055+0.j, 0.046+0.j, 0.037+0.j, 0.028+0.j, 0.019+0.j,
56
+ 0.010+0.j],
57
+ [1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
58
+ 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
59
+ 0.000+0.j],
60
+ [0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
61
+ 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
62
+ 0.000+0.j],
63
+ [0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j,
64
+ 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
65
+ 0.000+0.j],
66
+ [0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j,
67
+ 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
68
+ 0.000+0.j],
69
+ [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j,
70
+ 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
71
+ 0.000+0.j],
72
+ [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
73
+ 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
74
+ 0.000+0.j],
75
+ [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
76
+ 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
77
+ 0.000+0.j],
78
+ [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
79
+ 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j,
80
+ 0.000+0.j],
81
+ [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
82
+ 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j,
83
+ 0.000+0.j],
84
+ [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
85
+ 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j,
86
+ 0.000+0.j]]),
87
+ np.eye(11)),
88
+ # https://github.com/scipy/scipy/issues/4176
89
+ (matrix([[0, 1], [-1/2, -1]]),
90
+ (matrix([0, 3]).T @ matrix([0, 3]).T.T)),
91
+ # https://github.com/scipy/scipy/issues/4176
92
+ (matrix([[0, 1], [-1/2, -1]]),
93
+ (np.array(matrix([0, 3]).T @ matrix([0, 3]).T.T))),
94
+ ]
95
+
96
+ def test_continuous_squareness_and_shape(self):
97
+ nsq = np.ones((3, 2))
98
+ sq = np.eye(3)
99
+ assert_raises(ValueError, solve_continuous_lyapunov, nsq, sq)
100
+ assert_raises(ValueError, solve_continuous_lyapunov, sq, nsq)
101
+ assert_raises(ValueError, solve_continuous_lyapunov, sq, np.eye(2))
102
+
103
+ def check_continuous_case(self, a, q):
104
+ x = solve_continuous_lyapunov(a, q)
105
+ assert_array_almost_equal(
106
+ np.dot(a, x) + np.dot(x, a.conj().transpose()), q)
107
+
108
+ def check_discrete_case(self, a, q, method=None):
109
+ x = solve_discrete_lyapunov(a, q, method=method)
110
+ assert_array_almost_equal(
111
+ np.dot(np.dot(a, x), a.conj().transpose()) - x, -1.0*q)
112
+
113
+ @skip_xp_invalid_arg
114
+ def test_cases(self):
115
+ for case in self.cases:
116
+ self.check_continuous_case(case[0], case[1])
117
+ self.check_discrete_case(case[0], case[1])
118
+ self.check_discrete_case(case[0], case[1], method='direct')
119
+ self.check_discrete_case(case[0], case[1], method='bilinear')
120
+
121
+ @pytest.mark.parametrize("dtype_a", dtypes)
122
+ @pytest.mark.parametrize("dtype_q", dtypes)
123
+ def test_size_0(self, dtype_a, dtype_q):
124
+ rng = np.random.default_rng(234598235)
125
+
126
+ a = np.zeros((0, 0), dtype=dtype_a)
127
+ q = np.zeros((0, 0), dtype=dtype_q)
128
+ res = solve_continuous_lyapunov(a, q)
129
+
130
+ a = (rng.random((5, 5))*100).astype(dtype_a)
131
+ q = (rng.random((5, 5))*100).astype(dtype_q)
132
+ ref = solve_continuous_lyapunov(a, q)
133
+
134
+ assert res.shape == (0, 0)
135
+ assert res.dtype == ref.dtype
136
+
137
+
138
+ class TestSolveContinuousAre:
139
+ mat6 = _load_data('carex_6_data.npz')
140
+ mat15 = _load_data('carex_15_data.npz')
141
+ mat18 = _load_data('carex_18_data.npz')
142
+ mat19 = _load_data('carex_19_data.npz')
143
+ mat20 = _load_data('carex_20_data.npz')
144
+ cases = [
145
+ # Carex examples taken from (with default parameters):
146
+ # [1] P.BENNER, A.J. LAUB, V. MEHRMANN: 'A Collection of Benchmark
147
+ # Examples for the Numerical Solution of Algebraic Riccati
148
+ # Equations II: Continuous-Time Case', Tech. Report SPC 95_23,
149
+ # Fak. f. Mathematik, TU Chemnitz-Zwickau (Germany), 1995.
150
+ #
151
+ # The format of the data is (a, b, q, r, knownfailure), where
152
+ # knownfailure is None if the test passes or a string
153
+ # indicating the reason for failure.
154
+ #
155
+ # Test Case 0: carex #1
156
+ (np.diag([1.], 1),
157
+ np.array([[0], [1]]),
158
+ block_diag(1., 2.),
159
+ 1,
160
+ None),
161
+ # Test Case 1: carex #2
162
+ (np.array([[4, 3], [-4.5, -3.5]]),
163
+ np.array([[1], [-1]]),
164
+ np.array([[9, 6], [6, 4.]]),
165
+ 1,
166
+ None),
167
+ # Test Case 2: carex #3
168
+ (np.array([[0, 1, 0, 0],
169
+ [0, -1.89, 0.39, -5.53],
170
+ [0, -0.034, -2.98, 2.43],
171
+ [0.034, -0.0011, -0.99, -0.21]]),
172
+ np.array([[0, 0], [0.36, -1.6], [-0.95, -0.032], [0.03, 0]]),
173
+ np.array([[2.313, 2.727, 0.688, 0.023],
174
+ [2.727, 4.271, 1.148, 0.323],
175
+ [0.688, 1.148, 0.313, 0.102],
176
+ [0.023, 0.323, 0.102, 0.083]]),
177
+ np.eye(2),
178
+ None),
179
+ # Test Case 3: carex #4
180
+ (np.array([[-0.991, 0.529, 0, 0, 0, 0, 0, 0],
181
+ [0.522, -1.051, 0.596, 0, 0, 0, 0, 0],
182
+ [0, 0.522, -1.118, 0.596, 0, 0, 0, 0],
183
+ [0, 0, 0.522, -1.548, 0.718, 0, 0, 0],
184
+ [0, 0, 0, 0.922, -1.64, 0.799, 0, 0],
185
+ [0, 0, 0, 0, 0.922, -1.721, 0.901, 0],
186
+ [0, 0, 0, 0, 0, 0.922, -1.823, 1.021],
187
+ [0, 0, 0, 0, 0, 0, 0.922, -1.943]]),
188
+ np.array([[3.84, 4.00, 37.60, 3.08, 2.36, 2.88, 3.08, 3.00],
189
+ [-2.88, -3.04, -2.80, -2.32, -3.32, -3.82, -4.12, -3.96]]
190
+ ).T * 0.001,
191
+ np.array([[1.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.1],
192
+ [0.0, 1.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0],
193
+ [0.0, 0.0, 1.0, 0.0, 0.0, 0.5, 0.0, 0.0],
194
+ [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0],
195
+ [0.5, 0.1, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0],
196
+ [0.0, 0.0, 0.5, 0.0, 0.0, 0.1, 0.0, 0.0],
197
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.0],
198
+ [0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1]]),
199
+ np.eye(2),
200
+ None),
201
+ # Test Case 4: carex #5
202
+ (np.array(
203
+ [[-4.019, 5.120, 0., 0., -2.082, 0., 0., 0., 0.870],
204
+ [-0.346, 0.986, 0., 0., -2.340, 0., 0., 0., 0.970],
205
+ [-7.909, 15.407, -4.069, 0., -6.450, 0., 0., 0., 2.680],
206
+ [-21.816, 35.606, -0.339, -3.870, -17.800, 0., 0., 0., 7.390],
207
+ [-60.196, 98.188, -7.907, 0.340, -53.008, 0., 0., 0., 20.400],
208
+ [0, 0, 0, 0, 94.000, -147.200, 0., 53.200, 0.],
209
+ [0, 0, 0, 0, 0, 94.000, -147.200, 0, 0],
210
+ [0, 0, 0, 0, 0, 12.800, 0.000, -31.600, 0],
211
+ [0, 0, 0, 0, 12.800, 0.000, 0.000, 18.800, -31.600]]),
212
+ np.array([[0.010, -0.011, -0.151],
213
+ [0.003, -0.021, 0.000],
214
+ [0.009, -0.059, 0.000],
215
+ [0.024, -0.162, 0.000],
216
+ [0.068, -0.445, 0.000],
217
+ [0.000, 0.000, 0.000],
218
+ [0.000, 0.000, 0.000],
219
+ [0.000, 0.000, 0.000],
220
+ [0.000, 0.000, 0.000]]),
221
+ np.eye(9),
222
+ np.eye(3),
223
+ None),
224
+ # Test Case 5: carex #6
225
+ (mat6['A'], mat6['B'], mat6['Q'], mat6['R'], None),
226
+ # Test Case 6: carex #7
227
+ (np.array([[1, 0], [0, -2.]]),
228
+ np.array([[1e-6], [0]]),
229
+ np.ones((2, 2)),
230
+ 1.,
231
+ 'Bad residual accuracy'),
232
+ # Test Case 7: carex #8
233
+ (block_diag(-0.1, -0.02),
234
+ np.array([[0.100, 0.000], [0.001, 0.010]]),
235
+ np.array([[100, 1000], [1000, 10000]]),
236
+ np.ones((2, 2)) + block_diag(1e-6, 0),
237
+ None),
238
+ # Test Case 8: carex #9
239
+ (np.array([[0, 1e6], [0, 0]]),
240
+ np.array([[0], [1.]]),
241
+ np.eye(2),
242
+ 1.,
243
+ None),
244
+ # Test Case 9: carex #10
245
+ (np.array([[1.0000001, 1], [1., 1.0000001]]),
246
+ np.eye(2),
247
+ np.eye(2),
248
+ np.eye(2),
249
+ None),
250
+ # Test Case 10: carex #11
251
+ (np.array([[3, 1.], [4, 2]]),
252
+ np.array([[1], [1]]),
253
+ np.array([[-11, -5], [-5, -2.]]),
254
+ 1.,
255
+ None),
256
+ # Test Case 11: carex #12
257
+ (np.array([[7000000., 2000000., -0.],
258
+ [2000000., 6000000., -2000000.],
259
+ [0., -2000000., 5000000.]]) / 3,
260
+ np.eye(3),
261
+ np.array([[1., -2., -2.], [-2., 1., -2.], [-2., -2., 1.]]).dot(
262
+ np.diag([1e-6, 1, 1e6])).dot(
263
+ np.array([[1., -2., -2.], [-2., 1., -2.], [-2., -2., 1.]])) / 9,
264
+ np.eye(3) * 1e6,
265
+ 'Bad Residual Accuracy'),
266
+ # Test Case 12: carex #13
267
+ (np.array([[0, 0.4, 0, 0],
268
+ [0, 0, 0.345, 0],
269
+ [0, -0.524e6, -0.465e6, 0.262e6],
270
+ [0, 0, 0, -1e6]]),
271
+ np.array([[0, 0, 0, 1e6]]).T,
272
+ np.diag([1, 0, 1, 0]),
273
+ 1.,
274
+ None),
275
+ # Test Case 13: carex #14
276
+ (np.array([[-1e-6, 1, 0, 0],
277
+ [-1, -1e-6, 0, 0],
278
+ [0, 0, 1e-6, 1],
279
+ [0, 0, -1, 1e-6]]),
280
+ np.ones((4, 1)),
281
+ np.ones((4, 4)),
282
+ 1.,
283
+ None),
284
+ # Test Case 14: carex #15
285
+ (mat15['A'], mat15['B'], mat15['Q'], mat15['R'], None),
286
+ # Test Case 15: carex #16
287
+ (np.eye(64, 64, k=-1) + np.eye(64, 64)*(-2.) + np.rot90(
288
+ block_diag(1, np.zeros((62, 62)), 1)) + np.eye(64, 64, k=1),
289
+ np.eye(64),
290
+ np.eye(64),
291
+ np.eye(64),
292
+ None),
293
+ # Test Case 16: carex #17
294
+ (np.diag(np.ones((20, )), 1),
295
+ np.flipud(np.eye(21, 1)),
296
+ np.eye(21, 1) * np.eye(21, 1).T,
297
+ 1,
298
+ 'Bad Residual Accuracy'),
299
+ # Test Case 17: carex #18
300
+ (mat18['A'], mat18['B'], mat18['Q'], mat18['R'], None),
301
+ # Test Case 18: carex #19
302
+ (mat19['A'], mat19['B'], mat19['Q'], mat19['R'],
303
+ 'Bad Residual Accuracy'),
304
+ # Test Case 19: carex #20
305
+ (mat20['A'], mat20['B'], mat20['Q'], mat20['R'],
306
+ 'Bad Residual Accuracy')
307
+ ]
308
+ # Makes the minimum precision requirements customized to the test.
309
+ # Here numbers represent the number of decimals that agrees with zero
310
+ # matrix when the solution x is plugged in to the equation.
311
+ #
312
+ # res = array([[8e-3,1e-16],[1e-16,1e-20]]) --> min_decimal[k] = 2
313
+ #
314
+ # If the test is failing use "None" for that entry.
315
+ #
316
+ min_decimal = (14, 12, 13, 14, 11, 6, None, 5, 7, 14, 14,
317
+ None, 9, 14, 13, 14, None, 12, None, None)
318
+
319
+ @pytest.mark.parametrize("j, case", list(enumerate(cases)))
320
+ def test_solve_continuous_are(self, j, case):
321
+ """Checks if 0 = XA + A'X - XB(R)^{-1} B'X + Q is true"""
322
+ a, b, q, r, knownfailure = case
323
+ if knownfailure:
324
+ pytest.xfail(reason=knownfailure)
325
+
326
+ dec = self.min_decimal[j]
327
+ x = solve_continuous_are(a, b, q, r)
328
+ res = x @ a + a.conj().T @ x + q
329
+ out_fact = x @ b
330
+ res -= out_fact @ solve(np.atleast_2d(r), out_fact.conj().T)
331
+ assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
332
+
333
+
334
+ class TestSolveDiscreteAre:
335
+ cases = [
336
+ # Darex examples taken from (with default parameters):
337
+ # [1] P.BENNER, A.J. LAUB, V. MEHRMANN: 'A Collection of Benchmark
338
+ # Examples for the Numerical Solution of Algebraic Riccati
339
+ # Equations II: Discrete-Time Case', Tech. Report SPC 95_23,
340
+ # Fak. f. Mathematik, TU Chemnitz-Zwickau (Germany), 1995.
341
+ # [2] T. GUDMUNDSSON, C. KENNEY, A.J. LAUB: 'Scaling of the
342
+ # Discrete-Time Algebraic Riccati Equation to Enhance Stability
343
+ # of the Schur Solution Method', IEEE Trans.Aut.Cont., vol.37(4)
344
+ #
345
+ # The format of the data is (a, b, q, r, knownfailure), where
346
+ # knownfailure is None if the test passes or a string
347
+ # indicating the reason for failure.
348
+ #
349
+ # TEST CASE 0 : Complex a; real b, q, r
350
+ (np.array([[2, 1-2j], [0, -3j]]),
351
+ np.array([[0], [1]]),
352
+ np.array([[1, 0], [0, 2]]),
353
+ np.array([[1]]),
354
+ None),
355
+ # TEST CASE 1 :Real a, q, r; complex b
356
+ (np.array([[2, 1], [0, -1]]),
357
+ np.array([[-2j], [1j]]),
358
+ np.array([[1, 0], [0, 2]]),
359
+ np.array([[1]]),
360
+ None),
361
+ # TEST CASE 2 : Real a, b; complex q, r
362
+ (np.array([[3, 1], [0, -1]]),
363
+ np.array([[1, 2], [1, 3]]),
364
+ np.array([[1, 1+1j], [1-1j, 2]]),
365
+ np.array([[2, -2j], [2j, 3]]),
366
+ None),
367
+ # TEST CASE 3 : User-reported gh-2251 (Trac #1732)
368
+ (np.array([[0.63399379, 0.54906824, 0.76253406],
369
+ [0.5404729, 0.53745766, 0.08731853],
370
+ [0.27524045, 0.84922129, 0.4681622]]),
371
+ np.array([[0.96861695], [0.05532739], [0.78934047]]),
372
+ np.eye(3),
373
+ np.eye(1),
374
+ None),
375
+ # TEST CASE 4 : darex #1
376
+ (np.array([[4, 3], [-4.5, -3.5]]),
377
+ np.array([[1], [-1]]),
378
+ np.array([[9, 6], [6, 4]]),
379
+ np.array([[1]]),
380
+ None),
381
+ # TEST CASE 5 : darex #2
382
+ (np.array([[0.9512, 0], [0, 0.9048]]),
383
+ np.array([[4.877, 4.877], [-1.1895, 3.569]]),
384
+ np.array([[0.005, 0], [0, 0.02]]),
385
+ np.array([[1/3, 0], [0, 3]]),
386
+ None),
387
+ # TEST CASE 6 : darex #3
388
+ (np.array([[2, -1], [1, 0]]),
389
+ np.array([[1], [0]]),
390
+ np.array([[0, 0], [0, 1]]),
391
+ np.array([[0]]),
392
+ None),
393
+ # TEST CASE 7 : darex #4 (skipped the gen. Ric. term S)
394
+ (np.array([[0, 1], [0, -1]]),
395
+ np.array([[1, 0], [2, 1]]),
396
+ np.array([[-4, -4], [-4, 7]]) * (1/11),
397
+ np.array([[9, 3], [3, 1]]),
398
+ None),
399
+ # TEST CASE 8 : darex #5
400
+ (np.array([[0, 1], [0, 0]]),
401
+ np.array([[0], [1]]),
402
+ np.array([[1, 2], [2, 4]]),
403
+ np.array([[1]]),
404
+ None),
405
+ # TEST CASE 9 : darex #6
406
+ (np.array([[0.998, 0.067, 0, 0],
407
+ [-.067, 0.998, 0, 0],
408
+ [0, 0, 0.998, 0.153],
409
+ [0, 0, -.153, 0.998]]),
410
+ np.array([[0.0033, 0.0200],
411
+ [0.1000, -.0007],
412
+ [0.0400, 0.0073],
413
+ [-.0028, 0.1000]]),
414
+ np.array([[1.87, 0, 0, -0.244],
415
+ [0, 0.744, 0.205, 0],
416
+ [0, 0.205, 0.589, 0],
417
+ [-0.244, 0, 0, 1.048]]),
418
+ np.eye(2),
419
+ None),
420
+ # TEST CASE 10 : darex #7
421
+ (np.array([[0.984750, -.079903, 0.0009054, -.0010765],
422
+ [0.041588, 0.998990, -.0358550, 0.0126840],
423
+ [-.546620, 0.044916, -.3299100, 0.1931800],
424
+ [2.662400, -.100450, -.9245500, -.2632500]]),
425
+ np.array([[0.0037112, 0.0007361],
426
+ [-.0870510, 9.3411e-6],
427
+ [-1.198440, -4.1378e-4],
428
+ [-3.192700, 9.2535e-4]]),
429
+ np.eye(4)*1e-2,
430
+ np.eye(2),
431
+ None),
432
+ # TEST CASE 11 : darex #8
433
+ (np.array([[-0.6000000, -2.2000000, -3.6000000, -5.4000180],
434
+ [1.0000000, 0.6000000, 0.8000000, 3.3999820],
435
+ [0.0000000, 1.0000000, 1.8000000, 3.7999820],
436
+ [0.0000000, 0.0000000, 0.0000000, -0.9999820]]),
437
+ np.array([[1.0, -1.0, -1.0, -1.0],
438
+ [0.0, 1.0, -1.0, -1.0],
439
+ [0.0, 0.0, 1.0, -1.0],
440
+ [0.0, 0.0, 0.0, 1.0]]),
441
+ np.array([[2, 1, 3, 6],
442
+ [1, 2, 2, 5],
443
+ [3, 2, 6, 11],
444
+ [6, 5, 11, 22]]),
445
+ np.eye(4),
446
+ None),
447
+ # TEST CASE 12 : darex #9
448
+ (np.array([[95.4070, 1.9643, 0.3597, 0.0673, 0.0190],
449
+ [40.8490, 41.3170, 16.0840, 4.4679, 1.1971],
450
+ [12.2170, 26.3260, 36.1490, 15.9300, 12.3830],
451
+ [4.1118, 12.8580, 27.2090, 21.4420, 40.9760],
452
+ [0.1305, 0.5808, 1.8750, 3.6162, 94.2800]]) * 0.01,
453
+ np.array([[0.0434, -0.0122],
454
+ [2.6606, -1.0453],
455
+ [3.7530, -5.5100],
456
+ [3.6076, -6.6000],
457
+ [0.4617, -0.9148]]) * 0.01,
458
+ np.eye(5),
459
+ np.eye(2),
460
+ None),
461
+ # TEST CASE 13 : darex #10
462
+ (np.kron(np.eye(2), np.diag([1, 1], k=1)),
463
+ np.kron(np.eye(2), np.array([[0], [0], [1]])),
464
+ np.array([[1, 1, 0, 0, 0, 0],
465
+ [1, 1, 0, 0, 0, 0],
466
+ [0, 0, 0, 0, 0, 0],
467
+ [0, 0, 0, 1, -1, 0],
468
+ [0, 0, 0, -1, 1, 0],
469
+ [0, 0, 0, 0, 0, 0]]),
470
+ np.array([[3, 0], [0, 1]]),
471
+ None),
472
+ # TEST CASE 14 : darex #11
473
+ (0.001 * np.array(
474
+ [[870.1, 135.0, 11.59, .5014, -37.22, .3484, 0, 4.242, 7.249],
475
+ [76.55, 897.4, 12.72, 0.5504, -40.16, .3743, 0, 4.53, 7.499],
476
+ [-127.2, 357.5, 817, 1.455, -102.8, .987, 0, 11.85, 18.72],
477
+ [-363.5, 633.9, 74.91, 796.6, -273.5, 2.653, 0, 31.72, 48.82],
478
+ [-960, 1645.9, -128.9, -5.597, 71.42, 7.108, 0, 84.52, 125.9],
479
+ [-664.4, 112.96, -88.89, -3.854, 84.47, 13.6, 0, 144.3, 101.6],
480
+ [-410.2, 693, -54.71, -2.371, 66.49, 12.49, .1063, 99.97, 69.67],
481
+ [-179.9, 301.7, -23.93, -1.035, 60.59, 22.16, 0, 213.9, 35.54],
482
+ [-345.1, 580.4, -45.96, -1.989, 105.6, 19.86, 0, 219.1, 215.2]]),
483
+ np.array([[4.7600, -0.5701, -83.6800],
484
+ [0.8790, -4.7730, -2.7300],
485
+ [1.4820, -13.1200, 8.8760],
486
+ [3.8920, -35.1300, 24.8000],
487
+ [10.3400, -92.7500, 66.8000],
488
+ [7.2030, -61.5900, 38.3400],
489
+ [4.4540, -36.8300, 20.2900],
490
+ [1.9710, -15.5400, 6.9370],
491
+ [3.7730, -30.2800, 14.6900]]) * 0.001,
492
+ np.diag([50, 0, 0, 0, 50, 0, 0, 0, 0]),
493
+ np.eye(3),
494
+ None),
495
+ # TEST CASE 15 : darex #12 - numerically least accurate example
496
+ (np.array([[0, 1e6], [0, 0]]),
497
+ np.array([[0], [1]]),
498
+ np.eye(2),
499
+ np.array([[1]]),
500
+ None),
501
+ # TEST CASE 16 : darex #13
502
+ (np.array([[16, 10, -2],
503
+ [10, 13, -8],
504
+ [-2, -8, 7]]) * (1/9),
505
+ np.eye(3),
506
+ 1e6 * np.eye(3),
507
+ 1e6 * np.eye(3),
508
+ None),
509
+ # TEST CASE 17 : darex #14
510
+ (np.array([[1 - 1/1e8, 0, 0, 0],
511
+ [1, 0, 0, 0],
512
+ [0, 1, 0, 0],
513
+ [0, 0, 1, 0]]),
514
+ np.array([[1e-08], [0], [0], [0]]),
515
+ np.diag([0, 0, 0, 1]),
516
+ np.array([[0.25]]),
517
+ None),
518
+ # TEST CASE 18 : darex #15
519
+ (np.eye(100, k=1),
520
+ np.flipud(np.eye(100, 1)),
521
+ np.eye(100),
522
+ np.array([[1]]),
523
+ None)
524
+ ]
525
+
526
+ # Makes the minimum precision requirements customized to the test.
527
+ # Here numbers represent the number of decimals that agrees with zero
528
+ # matrix when the solution x is plugged in to the equation.
529
+ #
530
+ # res = array([[8e-3,1e-16],[1e-16,1e-20]]) --> min_decimal[k] = 2
531
+ #
532
+ # If the test is failing use "None" for that entry.
533
+ #
534
+ min_decimal = (12, 14, 13, 14, 13, 16, 18, 14, 14, 13,
535
+ 14, 13, 13, 14, 12, 2, 4, 6, 10)
536
+ max_tol = [1.5 * 10**-ind for ind in min_decimal]
537
+ # relaxed tolerance in gh-18012 after bump to OpenBLAS
538
+ max_tol[11] = 2.5e-13
539
+
540
+ # relaxed tolerance in gh-20335 for linux-aarch64 build on Cirrus
541
+ # with OpenBLAS from ubuntu jammy
542
+ max_tol[15] = 2.0e-2
543
+
544
+ # relaxed tolerance in gh-20335 for OpenBLAS 3.20 on ubuntu jammy
545
+ # bump not needed for OpenBLAS 3.26
546
+ max_tol[16] = 2.0e-4
547
+
548
+ @pytest.mark.parametrize("j, case", list(enumerate(cases)))
549
+ def test_solve_discrete_are(self, j, case):
550
+ """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true"""
551
+ a, b, q, r, knownfailure = case
552
+ if knownfailure:
553
+ pytest.xfail(reason=knownfailure)
554
+
555
+ atol = self.max_tol[j]
556
+
557
+ x = solve_discrete_are(a, b, q, r)
558
+ bH = b.conj().T
559
+ xa, xb = x @ a, x @ b
560
+
561
+ res = a.conj().T @ xa - x + q
562
+ res -= a.conj().T @ xb @ (solve(r + bH @ xb, bH) @ xa)
563
+
564
+ # changed from
565
+ # assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
566
+ # in gh-18012 as it's easier to relax a tolerance and allclose is
567
+ # preferred
568
+ assert_allclose(res, np.zeros_like(res), atol=atol)
569
+
570
+ def test_infeasible(self):
571
+ # An infeasible example taken from https://arxiv.org/abs/1505.04861v1
572
+ A = np.triu(np.ones((3, 3)))
573
+ A[0, 1] = -1
574
+ B = np.array([[1, 1, 0], [0, 0, 1]]).T
575
+ Q = np.full_like(A, -2) + np.diag([8, -1, -1.9])
576
+ R = np.diag([-10, 0.1])
577
+ assert_raises(LinAlgError, solve_continuous_are, A, B, Q, R)
578
+
579
+
580
+ class TestSolveCommonAre:
581
+ @pytest.mark.parametrize("solver", [solve_continuous_are, solve_discrete_are])
582
+ def test_with_skipped_array_argument_gh23336(self, solver):
583
+ # gh-23336 reported a failure when optional argument `e` was skipped
584
+ A = np.array([[-0.9, 0.25], [0, -1.1]])
585
+ B = np.array([[0.23], [0.45]])
586
+ Q = np.eye(2)
587
+ R = np.atleast_2d(0.45)
588
+ E = np.eye(2)
589
+ S = np.array([[0.1], [0.2]])
590
+
591
+ res = solver(A, B, Q, R, s=S)
592
+ ref = solver(A, B, Q, R, E, S)
593
+ np.testing.assert_allclose(res, ref)
594
+
595
+
596
+ def test_solve_generalized_continuous_are():
597
+ cases = [
598
+ # Two random examples differ by s term
599
+ # in the absence of any literature for demanding examples.
600
+ (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],
601
+ [4.617139e-02, 6.948286e-01, 3.444608e-02],
602
+ [9.713178e-02, 3.170995e-01, 4.387444e-01]]),
603
+ np.array([[3.815585e-01, 1.868726e-01],
604
+ [7.655168e-01, 4.897644e-01],
605
+ [7.951999e-01, 4.455862e-01]]),
606
+ np.eye(3),
607
+ np.eye(2),
608
+ np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],
609
+ [7.093648e-01, 6.797027e-01, 1.189977e-01],
610
+ [7.546867e-01, 6.550980e-01, 4.983641e-01]]),
611
+ np.zeros((3, 2)),
612
+ None),
613
+ (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],
614
+ [4.617139e-02, 6.948286e-01, 3.444608e-02],
615
+ [9.713178e-02, 3.170995e-01, 4.387444e-01]]),
616
+ np.array([[3.815585e-01, 1.868726e-01],
617
+ [7.655168e-01, 4.897644e-01],
618
+ [7.951999e-01, 4.455862e-01]]),
619
+ np.eye(3),
620
+ np.eye(2),
621
+ np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],
622
+ [7.093648e-01, 6.797027e-01, 1.189977e-01],
623
+ [7.546867e-01, 6.550980e-01, 4.983641e-01]]),
624
+ np.ones((3, 2)),
625
+ None)
626
+ ]
627
+
628
+ min_decimal = (10, 10)
629
+
630
+ def _test_factory(case, dec):
631
+ """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true"""
632
+ a, b, q, r, e, s, knownfailure = case
633
+ if knownfailure:
634
+ pytest.xfail(reason=knownfailure)
635
+
636
+ x = solve_continuous_are(a, b, q, r, e, s)
637
+ res = a.conj().T.dot(x.dot(e)) + e.conj().T.dot(x.dot(a)) + q
638
+ out_fact = e.conj().T.dot(x).dot(b) + s
639
+ res -= out_fact.dot(solve(np.atleast_2d(r), out_fact.conj().T))
640
+ assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
641
+
642
+ for ind, case in enumerate(cases):
643
+ _test_factory(case, min_decimal[ind])
644
+
645
+
646
+ def test_solve_generalized_discrete_are():
647
+ mat20170120 = _load_data('gendare_20170120_data.npz')
648
+
649
+ cases = [
650
+ # Two random examples differ by s term
651
+ # in the absence of any literature for demanding examples.
652
+ (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],
653
+ [4.617139e-02, 6.948286e-01, 3.444608e-02],
654
+ [9.713178e-02, 3.170995e-01, 4.387444e-01]]),
655
+ np.array([[3.815585e-01, 1.868726e-01],
656
+ [7.655168e-01, 4.897644e-01],
657
+ [7.951999e-01, 4.455862e-01]]),
658
+ np.eye(3),
659
+ np.eye(2),
660
+ np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],
661
+ [7.093648e-01, 6.797027e-01, 1.189977e-01],
662
+ [7.546867e-01, 6.550980e-01, 4.983641e-01]]),
663
+ np.zeros((3, 2)),
664
+ None),
665
+ (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],
666
+ [4.617139e-02, 6.948286e-01, 3.444608e-02],
667
+ [9.713178e-02, 3.170995e-01, 4.387444e-01]]),
668
+ np.array([[3.815585e-01, 1.868726e-01],
669
+ [7.655168e-01, 4.897644e-01],
670
+ [7.951999e-01, 4.455862e-01]]),
671
+ np.eye(3),
672
+ np.eye(2),
673
+ np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],
674
+ [7.093648e-01, 6.797027e-01, 1.189977e-01],
675
+ [7.546867e-01, 6.550980e-01, 4.983641e-01]]),
676
+ np.ones((3, 2)),
677
+ None),
678
+ # user-reported (under PR-6616) 20-Jan-2017
679
+ # tests against the case where E is None but S is provided
680
+ (mat20170120['A'],
681
+ mat20170120['B'],
682
+ mat20170120['Q'],
683
+ mat20170120['R'],
684
+ None,
685
+ mat20170120['S'],
686
+ None),
687
+ ]
688
+
689
+ max_atol = (1.5e-11, 1.5e-11, 3.5e-16)
690
+
691
+ def _test_factory(case, atol):
692
+ """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true"""
693
+ a, b, q, r, e, s, knownfailure = case
694
+ if knownfailure:
695
+ pytest.xfail(reason=knownfailure)
696
+
697
+ x = solve_discrete_are(a, b, q, r, e, s)
698
+ if e is None:
699
+ e = np.eye(a.shape[0])
700
+ if s is None:
701
+ s = np.zeros_like(b)
702
+ res = a.conj().T.dot(x.dot(a)) - e.conj().T.dot(x.dot(e)) + q
703
+ res -= (a.conj().T.dot(x.dot(b)) + s).dot(
704
+ solve(r+b.conj().T.dot(x.dot(b)),
705
+ (b.conj().T.dot(x.dot(a)) + s.conj().T)
706
+ )
707
+ )
708
+ # changed from:
709
+ # assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
710
+ # in gh-17950 because of a Linux 32 bit fail.
711
+ assert_allclose(res, np.zeros_like(res), atol=atol)
712
+
713
+ for ind, case in enumerate(cases):
714
+ _test_factory(case, max_atol[ind])
715
+
716
+
717
+ def test_are_validate_args():
718
+
719
+ def test_square_shape():
720
+ nsq = np.ones((3, 2))
721
+ sq = np.eye(3)
722
+ for x in (solve_continuous_are, solve_discrete_are):
723
+ assert_raises(ValueError, x, nsq, 1, 1, 1)
724
+ assert_raises(ValueError, x, sq, sq, nsq, 1)
725
+ assert_raises(ValueError, x, sq, sq, sq, nsq)
726
+ assert_raises(ValueError, x, sq, sq, sq, sq, nsq)
727
+
728
+ def test_compatible_sizes():
729
+ nsq = np.ones((3, 2))
730
+ sq = np.eye(4)
731
+ for x in (solve_continuous_are, solve_discrete_are):
732
+ assert_raises(ValueError, x, sq, nsq, 1, 1)
733
+ assert_raises(ValueError, x, sq, sq, sq, sq, sq, nsq)
734
+ assert_raises(ValueError, x, sq, sq, np.eye(3), sq)
735
+ assert_raises(ValueError, x, sq, sq, sq, np.eye(3))
736
+ assert_raises(ValueError, x, sq, sq, sq, sq, np.eye(3))
737
+
738
+ def test_symmetry():
739
+ nsym = np.arange(9).reshape(3, 3)
740
+ sym = np.eye(3)
741
+ for x in (solve_continuous_are, solve_discrete_are):
742
+ assert_raises(ValueError, x, sym, sym, nsym, sym)
743
+ assert_raises(ValueError, x, sym, sym, sym, nsym)
744
+
745
+ def test_singularity():
746
+ sing = np.full((3, 3), 1e12)
747
+ sing[2, 2] -= 1
748
+ sq = np.eye(3)
749
+ for x in (solve_continuous_are, solve_discrete_are):
750
+ assert_raises(ValueError, x, sq, sq, sq, sq, sing)
751
+
752
+ assert_raises(ValueError, solve_continuous_are, sq, sq, sq, sing)
753
+
754
+ def test_finiteness():
755
+ nm = np.full((2, 2), np.nan)
756
+ sq = np.eye(2)
757
+ for x in (solve_continuous_are, solve_discrete_are):
758
+ assert_raises(ValueError, x, nm, sq, sq, sq)
759
+ assert_raises(ValueError, x, sq, nm, sq, sq)
760
+ assert_raises(ValueError, x, sq, sq, nm, sq)
761
+ assert_raises(ValueError, x, sq, sq, sq, nm)
762
+ assert_raises(ValueError, x, sq, sq, sq, sq, nm)
763
+ assert_raises(ValueError, x, sq, sq, sq, sq, sq, nm)
764
+
765
+
766
+ class TestSolveSylvester:
767
+ cases = [
768
+ # empty cases
769
+ (np.empty((0, 0)),
770
+ np.empty((0, 0)),
771
+ np.empty((0, 0))),
772
+ (np.empty((0, 0)),
773
+ np.empty((2, 2)),
774
+ np.empty((0, 2))),
775
+ (np.empty((2, 2)),
776
+ np.empty((0, 0)),
777
+ np.empty((2, 0))),
778
+ # a, b, c all real.
779
+ (np.array([[1, 2], [0, 4]]),
780
+ np.array([[5, 6], [0, 8]]),
781
+ np.array([[9, 10], [11, 12]])),
782
+ # a, b, c all real, 4x4. a and b have non-trivial 2x2 blocks in their
783
+ # quasi-triangular form.
784
+ (np.array([[1.0, 0, 0, 0],
785
+ [0, 1.0, 2.0, 0.0],
786
+ [0, 0, 3.0, -4],
787
+ [0, 0, 2, 5]]),
788
+ np.array([[2.0, 0, 0, 1.0],
789
+ [0, 1.0, 0.0, 0.0],
790
+ [0, 0, 1.0, -1],
791
+ [0, 0, 1, 1]]),
792
+ np.array([[1.0, 0, 0, 0],
793
+ [0, 1.0, 0, 0],
794
+ [0, 0, 1.0, 0],
795
+ [0, 0, 0, 1.0]])),
796
+ # a, b, c all complex.
797
+ (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
798
+ np.array([[-1.0, 2j], [3.0, 4.0]]),
799
+ np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
800
+ # a and b real; c complex.
801
+ (np.array([[1.0, 2.0], [3.0, 5.0]]),
802
+ np.array([[-1.0, 0], [3.0, 4.0]]),
803
+ np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
804
+ # a and c complex; b real.
805
+ (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
806
+ np.array([[-1.0, 0], [3.0, 4.0]]),
807
+ np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
808
+ # a complex; b and c real.
809
+ (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
810
+ np.array([[-1.0, 0], [3.0, 4.0]]),
811
+ np.array([[2.0, 2.0], [-1.0, 2.0]])),
812
+ # not square matrices, real
813
+ (np.array([[8, 1, 6], [3, 5, 7], [4, 9, 2]]),
814
+ np.array([[2, 3], [4, 5]]),
815
+ np.array([[1, 2], [3, 4], [5, 6]])),
816
+ # not square matrices, complex
817
+ (np.array([[8, 1j, 6+2j], [3, 5, 7], [4, 9, 2]]),
818
+ np.array([[2, 3], [4, 5-1j]]),
819
+ np.array([[1, 2j], [3, 4j], [5j, 6+7j]])),
820
+ ]
821
+
822
+ def check_case(self, a, b, c):
823
+ x = solve_sylvester(a, b, c)
824
+ assert_array_almost_equal(np.dot(a, x) + np.dot(x, b), c)
825
+
826
+ def test_cases(self):
827
+ for case in self.cases:
828
+ self.check_case(case[0], case[1], case[2])
829
+
830
+ def test_trivial(self):
831
+ a = np.array([[1.0, 0.0], [0.0, 1.0]])
832
+ b = np.array([[1.0]])
833
+ c = np.array([2.0, 2.0]).reshape(-1, 1)
834
+ x = solve_sylvester(a, b, c)
835
+ assert_array_almost_equal(x, np.array([1.0, 1.0]).reshape(-1, 1))
836
+
837
+ # Feel free to adjust this to test fewer dtypes or random selections rather than
838
+ # the Cartesian product. It doesn't take very long to test all combinations,
839
+ # though, so we'll start there and trim it down as we see fit.
840
+ @pytest.mark.parametrize("dtype_a", dtypes)
841
+ @pytest.mark.parametrize("dtype_b", dtypes)
842
+ @pytest.mark.parametrize("dtype_q", dtypes)
843
+ @pytest.mark.parametrize("m", [0, 3])
844
+ @pytest.mark.parametrize("n", [0, 3])
845
+ def test_size_0(self, m, n, dtype_a, dtype_b, dtype_q):
846
+ if m == n != 0:
847
+ pytest.skip('m = n != 0 is not a case that needs to be tested here.')
848
+
849
+ rng = np.random.default_rng(598435298262546)
850
+
851
+ a = np.zeros((m, m), dtype=dtype_a)
852
+ b = np.zeros((n, n), dtype=dtype_b)
853
+ q = np.zeros((m, n), dtype=dtype_q)
854
+ res = solve_sylvester(a, b, q)
855
+
856
+ a = (rng.random((5, 5))*100).astype(dtype_a)
857
+ b = (rng.random((6, 6))*100).astype(dtype_b)
858
+ q = (rng.random((5, 6))*100).astype(dtype_q)
859
+ ref = solve_sylvester(a, b, q)
860
+
861
+ assert res.shape == (m, n)
862
+ assert res.dtype == ref.dtype
.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_special_matrices.py ADDED
@@ -0,0 +1,619 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import numpy as np
3
+ from numpy import arange, array, eye, copy, sqrt
4
+ from numpy.testing import (assert_equal, assert_array_equal,
5
+ assert_array_almost_equal, assert_allclose)
6
+ from pytest import raises as assert_raises
7
+
8
+ from scipy.fft import fft
9
+ from scipy.special import comb
10
+ from scipy.linalg import (toeplitz, hankel, circulant, hadamard, leslie, dft,
11
+ companion, block_diag,
12
+ helmert, hilbert, invhilbert, pascal, invpascal,
13
+ fiedler, fiedler_companion, eigvals,
14
+ convolution_matrix)
15
+ from numpy.linalg import cond
16
+ from scipy._lib._array_api import (make_xp_test_case, xp_assert_equal, xp_size,
17
+ xp_default_dtype)
18
+
19
+
20
+ class TestToeplitz:
21
+
22
+ def test_basic(self):
23
+ y = toeplitz([1, 2, 3])
24
+ assert_array_equal(y, [[1, 2, 3], [2, 1, 2], [3, 2, 1]])
25
+ y = toeplitz([1, 2, 3], [1, 4, 5])
26
+ assert_array_equal(y, [[1, 4, 5], [2, 1, 4], [3, 2, 1]])
27
+
28
+ def test_complex_01(self):
29
+ data = (1.0 + arange(3.0)) * (1.0 + 1.0j)
30
+ x = copy(data)
31
+ t = toeplitz(x)
32
+ # Calling toeplitz should not change x.
33
+ assert_array_equal(x, data)
34
+ # According to the docstring, x should be the first column of t.
35
+ col0 = t[:, 0]
36
+ assert_array_equal(col0, data)
37
+ assert_array_equal(t[0, 1:], data[1:].conj())
38
+
39
+ def test_scalar_00(self):
40
+ """Scalar arguments still produce a 2D array."""
41
+ t = toeplitz(10)
42
+ assert_array_equal(t, [[10]])
43
+ t = toeplitz(10, 20)
44
+ assert_array_equal(t, [[10]])
45
+
46
+ def test_scalar_01(self):
47
+ c = array([1, 2, 3])
48
+ t = toeplitz(c, 1)
49
+ assert_array_equal(t, [[1], [2], [3]])
50
+
51
+ def test_scalar_02(self):
52
+ c = array([1, 2, 3])
53
+ t = toeplitz(c, array(1))
54
+ assert_array_equal(t, [[1], [2], [3]])
55
+
56
+ def test_scalar_03(self):
57
+ c = array([1, 2, 3])
58
+ t = toeplitz(c, array([1]))
59
+ assert_array_equal(t, [[1], [2], [3]])
60
+
61
+ def test_scalar_04(self):
62
+ r = array([10, 2, 3])
63
+ t = toeplitz(1, r)
64
+ assert_array_equal(t, [[1, 2, 3]])
65
+
66
+
67
+ class TestHankel:
68
+ def test_basic(self):
69
+ y = hankel([1, 2, 3])
70
+ assert_array_equal(y, [[1, 2, 3], [2, 3, 0], [3, 0, 0]])
71
+ y = hankel([1, 2, 3], [3, 4, 5])
72
+ assert_array_equal(y, [[1, 2, 3], [2, 3, 4], [3, 4, 5]])
73
+
74
+
75
+ class TestCirculant:
76
+ def test_basic(self):
77
+ y = circulant([1, 2, 3])
78
+ assert_array_equal(y, [[1, 3, 2], [2, 1, 3], [3, 2, 1]])
79
+
80
+
81
+ class TestHadamard:
82
+
83
+ def test_basic(self):
84
+
85
+ y = hadamard(1)
86
+ assert_array_equal(y, [[1]])
87
+
88
+ y = hadamard(2, dtype=float)
89
+ assert_array_equal(y, [[1.0, 1.0], [1.0, -1.0]])
90
+
91
+ y = hadamard(4)
92
+ assert_array_equal(y, [[1, 1, 1, 1],
93
+ [1, -1, 1, -1],
94
+ [1, 1, -1, -1],
95
+ [1, -1, -1, 1]])
96
+
97
+ assert_raises(ValueError, hadamard, 0)
98
+ assert_raises(ValueError, hadamard, 5)
99
+
100
+
101
+ class TestLeslie:
102
+
103
+ def test_bad_shapes(self):
104
+ assert_raises(ValueError, leslie, [[1, 1], [2, 2]], [3, 4, 5])
105
+ assert_raises(ValueError, leslie, [1, 2], [1, 2])
106
+ assert_raises(ValueError, leslie, [1], [])
107
+
108
+ def test_basic(self):
109
+ a = leslie([1, 2, 3], [0.25, 0.5])
110
+ expected = array([[1.0, 2.0, 3.0],
111
+ [0.25, 0.0, 0.0],
112
+ [0.0, 0.5, 0.0]])
113
+ assert_array_equal(a, expected)
114
+
115
+
116
+ class TestCompanion:
117
+
118
+ def test_bad_shapes(self):
119
+ assert_raises(ValueError, companion, [0, 4, 5])
120
+ assert_raises(ValueError, companion, [1])
121
+ assert_raises(ValueError, companion, [])
122
+
123
+ def test_basic(self):
124
+ c = companion([1, 2, 3])
125
+ expected = array([
126
+ [-2.0, -3.0],
127
+ [1.0, 0.0]])
128
+ assert_array_equal(c, expected)
129
+
130
+ c = companion([2.0, 5.0, -10.0])
131
+ expected = array([
132
+ [-2.5, 5.0],
133
+ [1.0, 0.0]])
134
+ assert_array_equal(c, expected)
135
+
136
+ c = companion([(1.0, 2.0, 3.0),
137
+ (4.0, 5.0, 6.0)])
138
+ expected = array([
139
+ ([-2.00, -3.00],
140
+ [+1.00, +0.00]),
141
+ ([-1.25, -1.50],
142
+ [+1.00, +0.00])
143
+ ])
144
+ assert_array_equal(c, expected)
145
+
146
+
147
+ @make_xp_test_case(block_diag)
148
+ class TestBlockDiag:
149
+ def test_basic(self, xp):
150
+ dtype = xp.asarray(1).dtype
151
+ x = block_diag(xp.eye(2, dtype=dtype), xp.asarray([[1, 2], [3, 4], [5, 6]]),
152
+ xp.asarray([[1, 2, 3]]))
153
+ xp_assert_equal(x, xp.asarray([[1, 0, 0, 0, 0, 0, 0],
154
+ [0, 1, 0, 0, 0, 0, 0],
155
+ [0, 0, 1, 2, 0, 0, 0],
156
+ [0, 0, 3, 4, 0, 0, 0],
157
+ [0, 0, 5, 6, 0, 0, 0],
158
+ [0, 0, 0, 0, 1, 2, 3]]))
159
+
160
+ def test_dtype(self, xp):
161
+ x = block_diag(xp.asarray([[1.5]]))
162
+ assert x.dtype == xp_default_dtype(xp)
163
+
164
+ x = block_diag(xp.asarray([[True]]))
165
+ assert x.dtype == xp.bool
166
+
167
+ def test_mixed_dtypes(self, xp):
168
+ actual = block_diag(xp.asarray([[1.]]), xp.asarray([[1j]]))
169
+ desired = xp.asarray([[1, 0], [0, 1j]])
170
+ xp_assert_equal(actual, desired)
171
+
172
+ def test_scalar_and_1d_args(self, xp):
173
+ a = block_diag(xp.asarray(1))
174
+ assert a.shape == (1, 1)
175
+ xp_assert_equal(a, xp.asarray([[1]]))
176
+
177
+ a = block_diag(xp.asarray([2, 3]), xp.asarray(4))
178
+ xp_assert_equal(a, xp.asarray([[2, 3, 0], [0, 0, 4]]))
179
+
180
+ def test_no_args(self):
181
+ a = block_diag()
182
+ assert a.ndim == 2
183
+ assert a.nbytes == 0
184
+
185
+ def test_empty_matrix_arg(self, xp):
186
+ # regression test for gh-4596: check the shape of the result
187
+ # for empty matrix inputs. Empty matrices are no longer ignored
188
+ # (gh-4908) it is viewed as a shape (1, 0) matrix.
189
+ dtype = xp.asarray(1).dtype
190
+ a = block_diag(xp.asarray([[1, 0], [0, 1]]),
191
+ xp.asarray([], dtype=dtype),
192
+ xp.asarray([[2, 3], [4, 5], [6, 7]]))
193
+ xp_assert_equal(a, xp.asarray([[1, 0, 0, 0],
194
+ [0, 1, 0, 0],
195
+ [0, 0, 0, 0],
196
+ [0, 0, 2, 3],
197
+ [0, 0, 4, 5],
198
+ [0, 0, 6, 7]]))
199
+
200
+ @pytest.mark.skip_xp_backends("dask.array", reason="dask/dask#11800")
201
+ def test_zerosized_matrix_arg(self, xp):
202
+ # test for gh-4908: check the shape of the result for
203
+ # zero-sized matrix inputs, i.e. matrices with shape (0,n) or (n,0).
204
+ # note that [[]] takes shape (1,0)
205
+ dtype = xp.asarray(1).dtype
206
+ a = block_diag(xp.asarray([[1, 0], [0, 1]]),
207
+ xp.asarray([[]], dtype=dtype),
208
+ xp.asarray([[2, 3], [4, 5], [6, 7]]),
209
+ xp.zeros([0, 2], dtype=dtype))
210
+ xp_assert_equal(a, xp.asarray([[1, 0, 0, 0, 0, 0],
211
+ [0, 1, 0, 0, 0, 0],
212
+ [0, 0, 0, 0, 0, 0],
213
+ [0, 0, 2, 3, 0, 0],
214
+ [0, 0, 4, 5, 0, 0],
215
+ [0, 0, 6, 7, 0, 0]]))
216
+
217
+
218
+ class TestHelmert:
219
+
220
+ def test_orthogonality(self):
221
+ for n in range(1, 7):
222
+ H = helmert(n, full=True)
223
+ Id = np.eye(n)
224
+ assert_allclose(H.dot(H.T), Id, atol=1e-12)
225
+ assert_allclose(H.T.dot(H), Id, atol=1e-12)
226
+
227
+ def test_subspace(self):
228
+ for n in range(2, 7):
229
+ H_full = helmert(n, full=True)
230
+ H_partial = helmert(n)
231
+ for U in H_full[1:, :].T, H_partial.T:
232
+ C = np.eye(n) - np.full((n, n), 1 / n)
233
+ assert_allclose(U.dot(U.T), C)
234
+ assert_allclose(U.T.dot(U), np.eye(n-1), atol=1e-12)
235
+
236
+
237
+ class TestHilbert:
238
+
239
+ def test_basic(self):
240
+ h3 = array([[1.0, 1/2., 1/3.],
241
+ [1/2., 1/3., 1/4.],
242
+ [1/3., 1/4., 1/5.]])
243
+ assert_array_almost_equal(hilbert(3), h3)
244
+
245
+ assert_array_equal(hilbert(1), [[1.0]])
246
+
247
+ h0 = hilbert(0)
248
+ assert_equal(h0.shape, (0, 0))
249
+
250
+
251
+ class TestInvHilbert:
252
+
253
+ def test_basic(self):
254
+ invh1 = array([[1]])
255
+ assert_array_equal(invhilbert(1, exact=True), invh1)
256
+ assert_array_equal(invhilbert(1), invh1)
257
+
258
+ invh2 = array([[4, -6],
259
+ [-6, 12]])
260
+ assert_array_equal(invhilbert(2, exact=True), invh2)
261
+ assert_array_almost_equal(invhilbert(2), invh2)
262
+
263
+ invh3 = array([[9, -36, 30],
264
+ [-36, 192, -180],
265
+ [30, -180, 180]])
266
+ assert_array_equal(invhilbert(3, exact=True), invh3)
267
+ assert_array_almost_equal(invhilbert(3), invh3)
268
+
269
+ invh4 = array([[16, -120, 240, -140],
270
+ [-120, 1200, -2700, 1680],
271
+ [240, -2700, 6480, -4200],
272
+ [-140, 1680, -4200, 2800]])
273
+ assert_array_equal(invhilbert(4, exact=True), invh4)
274
+ assert_array_almost_equal(invhilbert(4), invh4)
275
+
276
+ invh5 = array([[25, -300, 1050, -1400, 630],
277
+ [-300, 4800, -18900, 26880, -12600],
278
+ [1050, -18900, 79380, -117600, 56700],
279
+ [-1400, 26880, -117600, 179200, -88200],
280
+ [630, -12600, 56700, -88200, 44100]])
281
+ assert_array_equal(invhilbert(5, exact=True), invh5)
282
+ assert_array_almost_equal(invhilbert(5), invh5)
283
+
284
+ invh17 = array([
285
+ [289, -41616, 1976760, -46124400, 629598060, -5540462928,
286
+ 33374693352, -143034400080, 446982500250, -1033026222800,
287
+ 1774926873720, -2258997839280, 2099709530100, -1384423866000,
288
+ 613101997800, -163493866080, 19835652870],
289
+ [-41616, 7990272, -426980160, 10627061760, -151103534400,
290
+ 1367702848512, -8410422724704, 36616806420480, -115857864064800,
291
+ 270465047424000, -468580694662080, 600545887119360,
292
+ -561522320049600, 372133135180800, -165537539406000,
293
+ 44316454993920, -5395297580640],
294
+ [1976760, -426980160, 24337869120, -630981792000, 9228108708000,
295
+ -85267724461920, 532660105897920, -2348052711713280,
296
+ 7504429831470000, -17664748409880000, 30818191841236800,
297
+ -39732544853164800, 37341234283298400, -24857330514030000,
298
+ 11100752642520000, -2982128117299200, 364182586693200],
299
+ [-46124400, 10627061760, -630981792000, 16826181120000,
300
+ -251209625940000, 2358021022156800, -14914482965141760,
301
+ 66409571644416000, -214015221119700000, 507295338950400000,
302
+ -890303319857952000, 1153715376477081600, -1089119333262870000,
303
+ 727848632044800000, -326170262829600000, 87894302404608000,
304
+ -10763618673376800],
305
+ [629598060, -151103534400, 9228108708000,
306
+ -251209625940000, 3810012660090000, -36210360321495360,
307
+ 231343968720664800, -1038687206500944000, 3370739732635275000,
308
+ -8037460526495400000, 14178080368737885600, -18454939322943942000,
309
+ 17489975175339030000, -11728977435138600000, 5272370630081100000,
310
+ -1424711708039692800, 174908803442373000],
311
+ [-5540462928, 1367702848512, -85267724461920, 2358021022156800,
312
+ -36210360321495360, 347619459086355456, -2239409617216035264,
313
+ 10124803292907663360, -33052510749726468000,
314
+ 79217210949138662400, -140362995650505067440,
315
+ 183420385176741672960, -174433352415381259200,
316
+ 117339159519533952000, -52892422160973595200,
317
+ 14328529177999196160, -1763080738699119840],
318
+ [33374693352, -8410422724704, 532660105897920,
319
+ -14914482965141760, 231343968720664800, -2239409617216035264,
320
+ 14527452132196331328, -66072377044391477760,
321
+ 216799987176909536400, -521925895055522958000,
322
+ 928414062734059661760, -1217424500995626443520,
323
+ 1161358898976091015200, -783401860847777371200,
324
+ 354015418167362952000, -96120549902411274240,
325
+ 11851820521255194480],
326
+ [-143034400080, 36616806420480, -2348052711713280,
327
+ 66409571644416000, -1038687206500944000, 10124803292907663360,
328
+ -66072377044391477760, 302045152202932469760,
329
+ -995510145200094810000, 2405996923185123840000,
330
+ -4294704507885446054400, 5649058909023744614400,
331
+ -5403874060541811254400, 3654352703663101440000,
332
+ -1655137020003255360000, 450325202737117593600,
333
+ -55630994283442749600],
334
+ [446982500250, -115857864064800, 7504429831470000,
335
+ -214015221119700000, 3370739732635275000, -33052510749726468000,
336
+ 216799987176909536400, -995510145200094810000,
337
+ 3293967392206196062500, -7988661659013106500000,
338
+ 14303908928401362270000, -18866974090684772052000,
339
+ 18093328327706957325000, -12263364009096700500000,
340
+ 5565847995255512250000, -1517208935002984080000,
341
+ 187754605706619279900],
342
+ [-1033026222800, 270465047424000, -17664748409880000,
343
+ 507295338950400000, -8037460526495400000, 79217210949138662400,
344
+ -521925895055522958000, 2405996923185123840000,
345
+ -7988661659013106500000, 19434404971634224000000,
346
+ -34894474126569249192000, 46141453390504792320000,
347
+ -44349976506971935800000, 30121928988527376000000,
348
+ -13697025107665828500000, 3740200989399948902400,
349
+ -463591619028689580000],
350
+ [1774926873720, -468580694662080,
351
+ 30818191841236800, -890303319857952000, 14178080368737885600,
352
+ -140362995650505067440, 928414062734059661760,
353
+ -4294704507885446054400, 14303908928401362270000,
354
+ -34894474126569249192000, 62810053427824648545600,
355
+ -83243376594051600326400, 80177044485212743068000,
356
+ -54558343880470209780000, 24851882355348879230400,
357
+ -6797096028813368678400, 843736746632215035600],
358
+ [-2258997839280, 600545887119360, -39732544853164800,
359
+ 1153715376477081600, -18454939322943942000, 183420385176741672960,
360
+ -1217424500995626443520, 5649058909023744614400,
361
+ -18866974090684772052000, 46141453390504792320000,
362
+ -83243376594051600326400, 110552468520163390156800,
363
+ -106681852579497947388000, 72720410752415168870400,
364
+ -33177973900974346080000, 9087761081682520473600,
365
+ -1129631016152221783200],
366
+ [2099709530100, -561522320049600, 37341234283298400,
367
+ -1089119333262870000, 17489975175339030000,
368
+ -174433352415381259200, 1161358898976091015200,
369
+ -5403874060541811254400, 18093328327706957325000,
370
+ -44349976506971935800000, 80177044485212743068000,
371
+ -106681852579497947388000, 103125790826848015808400,
372
+ -70409051543137015800000, 32171029219823375700000,
373
+ -8824053728865840192000, 1098252376814660067000],
374
+ [-1384423866000, 372133135180800,
375
+ -24857330514030000, 727848632044800000, -11728977435138600000,
376
+ 117339159519533952000, -783401860847777371200,
377
+ 3654352703663101440000, -12263364009096700500000,
378
+ 30121928988527376000000, -54558343880470209780000,
379
+ 72720410752415168870400, -70409051543137015800000,
380
+ 48142941226076592000000, -22027500987368499000000,
381
+ 6049545098753157120000, -753830033789944188000],
382
+ [613101997800, -165537539406000,
383
+ 11100752642520000, -326170262829600000, 5272370630081100000,
384
+ -52892422160973595200, 354015418167362952000,
385
+ -1655137020003255360000, 5565847995255512250000,
386
+ -13697025107665828500000, 24851882355348879230400,
387
+ -33177973900974346080000, 32171029219823375700000,
388
+ -22027500987368499000000, 10091416708498869000000,
389
+ -2774765838662800128000, 346146444087219270000],
390
+ [-163493866080, 44316454993920, -2982128117299200,
391
+ 87894302404608000, -1424711708039692800,
392
+ 14328529177999196160, -96120549902411274240,
393
+ 450325202737117593600, -1517208935002984080000,
394
+ 3740200989399948902400, -6797096028813368678400,
395
+ 9087761081682520473600, -8824053728865840192000,
396
+ 6049545098753157120000, -2774765838662800128000,
397
+ 763806510427609497600, -95382575704033754400],
398
+ [19835652870, -5395297580640, 364182586693200, -10763618673376800,
399
+ 174908803442373000, -1763080738699119840, 11851820521255194480,
400
+ -55630994283442749600, 187754605706619279900,
401
+ -463591619028689580000, 843736746632215035600,
402
+ -1129631016152221783200, 1098252376814660067000,
403
+ -753830033789944188000, 346146444087219270000,
404
+ -95382575704033754400, 11922821963004219300]
405
+ ])
406
+ assert_array_equal(invhilbert(17, exact=True), invh17)
407
+ assert_allclose(invhilbert(17), invh17.astype(float), rtol=1e-12)
408
+
409
+ def test_inverse(self):
410
+ for n in range(1, 10):
411
+ a = hilbert(n)
412
+ b = invhilbert(n)
413
+ # The Hilbert matrix is increasingly badly conditioned,
414
+ # so take that into account in the test
415
+ c = cond(a)
416
+ assert_allclose(a.dot(b), eye(n), atol=1e-15*c, rtol=1e-15*c)
417
+
418
+
419
+ class TestPascal:
420
+
421
+ cases = [
422
+ (1, array([[1]]), array([[1]])),
423
+ (2, array([[1, 1],
424
+ [1, 2]]),
425
+ array([[1, 0],
426
+ [1, 1]])),
427
+ (3, array([[1, 1, 1],
428
+ [1, 2, 3],
429
+ [1, 3, 6]]),
430
+ array([[1, 0, 0],
431
+ [1, 1, 0],
432
+ [1, 2, 1]])),
433
+ (4, array([[1, 1, 1, 1],
434
+ [1, 2, 3, 4],
435
+ [1, 3, 6, 10],
436
+ [1, 4, 10, 20]]),
437
+ array([[1, 0, 0, 0],
438
+ [1, 1, 0, 0],
439
+ [1, 2, 1, 0],
440
+ [1, 3, 3, 1]])),
441
+ ]
442
+
443
+ def check_case(self, n, sym, low):
444
+ assert_array_equal(pascal(n), sym)
445
+ assert_array_equal(pascal(n, kind='lower'), low)
446
+ assert_array_equal(pascal(n, kind='upper'), low.T)
447
+ assert_array_almost_equal(pascal(n, exact=False), sym)
448
+ assert_array_almost_equal(pascal(n, exact=False, kind='lower'), low)
449
+ assert_array_almost_equal(pascal(n, exact=False, kind='upper'), low.T)
450
+
451
+ def test_cases(self):
452
+ for n, sym, low in self.cases:
453
+ self.check_case(n, sym, low)
454
+
455
+ def test_big(self):
456
+ p = pascal(50)
457
+ assert p[-1, -1] == comb(98, 49, exact=True)
458
+
459
+ def test_threshold(self):
460
+ # Regression test. An early version of `pascal` returned an
461
+ # array of type np.uint64 for n=35, but that data type is too small
462
+ # to hold p[-1, -1]. The second assert_equal below would fail
463
+ # because p[-1, -1] overflowed.
464
+ p = pascal(34)
465
+ assert_equal(2*p.item(-1, -2), p.item(-1, -1), err_msg="n = 34")
466
+ p = pascal(35)
467
+ assert_equal(2.*p.item(-1, -2), 1.*p.item(-1, -1), err_msg="n = 35")
468
+
469
+
470
+ def test_invpascal():
471
+
472
+ def check_invpascal(n, kind, exact):
473
+ ip = invpascal(n, kind=kind, exact=exact)
474
+ p = pascal(n, kind=kind, exact=exact)
475
+ # Matrix-multiply ip and p, and check that we get the identity matrix.
476
+ # We can't use the simple expression e = ip.dot(p), because when
477
+ # n < 35 and exact is True, p.dtype is np.uint64 and ip.dtype is
478
+ # np.int64. The product of those dtypes is np.float64, which loses
479
+ # precision when n is greater than 18. Instead we'll cast both to
480
+ # object arrays, and then multiply.
481
+ e = ip.astype(object).dot(p.astype(object))
482
+ assert_array_equal(e, eye(n), err_msg=f"n={n} kind={kind!r} exact={exact!r}")
483
+
484
+ kinds = ['symmetric', 'lower', 'upper']
485
+
486
+ ns = [1, 2, 5, 18]
487
+ for n in ns:
488
+ for kind in kinds:
489
+ for exact in [True, False]:
490
+ check_invpascal(n, kind, exact)
491
+
492
+ ns = [19, 34, 35, 50]
493
+ for n in ns:
494
+ for kind in kinds:
495
+ check_invpascal(n, kind, True)
496
+
497
+
498
+ def test_dft():
499
+ m = dft(2)
500
+ expected = array([[1.0, 1.0], [1.0, -1.0]])
501
+ assert_array_almost_equal(m, expected)
502
+ m = dft(2, scale='n')
503
+ assert_array_almost_equal(m, expected/2.0)
504
+ m = dft(2, scale='sqrtn')
505
+ assert_array_almost_equal(m, expected/sqrt(2.0))
506
+
507
+ x = array([0, 1, 2, 3, 4, 5, 0, 1])
508
+ m = dft(8)
509
+ mx = m.dot(x)
510
+ fx = fft(x)
511
+ assert_array_almost_equal(mx, fx)
512
+
513
+
514
+ @make_xp_test_case(fiedler)
515
+ def test_fiedler(xp):
516
+ f = fiedler(xp.asarray([]))
517
+ assert xp_size(f) == 0
518
+ assert f.shape == (0, 0)
519
+
520
+ f = fiedler(xp.asarray([123.]))
521
+ xp_assert_equal(f, xp.asarray([[0.]]))
522
+
523
+ f = fiedler(xp.arange(1, 7))
524
+ des = xp.asarray([[0, 1, 2, 3, 4, 5],
525
+ [1, 0, 1, 2, 3, 4],
526
+ [2, 1, 0, 1, 2, 3],
527
+ [3, 2, 1, 0, 1, 2],
528
+ [4, 3, 2, 1, 0, 1],
529
+ [5, 4, 3, 2, 1, 0]])
530
+ xp_assert_equal(f, des)
531
+
532
+
533
+ def test_fiedler_companion():
534
+ fc = fiedler_companion([])
535
+ assert_equal(fc.size, 0)
536
+ fc = fiedler_companion([1.])
537
+ assert_equal(fc.size, 0)
538
+ assert_equal(fc.shape, (0, 0))
539
+ fc = fiedler_companion([1., 2.])
540
+ assert_array_equal(fc, np.array([[-2.]]))
541
+ fc = fiedler_companion([1e-12, 2., 3.])
542
+ assert_array_almost_equal(fc, companion([1e-12, 2., 3.]))
543
+ with assert_raises(ValueError):
544
+ fiedler_companion([0, 1, 2])
545
+ fc = fiedler_companion([1., -16., 86., -176., 105.])
546
+ assert_array_almost_equal(eigvals(fc),
547
+ np.array([7., 5., 3., 1.]))
548
+
549
+
550
+ class TestConvolutionMatrix:
551
+ """
552
+ Test convolution_matrix vs. numpy.convolve for various parameters.
553
+ """
554
+
555
+ def create_vector(self, n, cpx):
556
+ """Make a complex or real test vector of length n."""
557
+ x = np.linspace(-2.5, 2.2, n)
558
+ if cpx:
559
+ x = x + 1j*np.linspace(-1.5, 3.1, n)
560
+ return x
561
+
562
+ def test_bad_n(self):
563
+ # n must be a positive integer
564
+ with pytest.raises(ValueError, match='n must be a positive integer'):
565
+ convolution_matrix([1, 2, 3], 0)
566
+
567
+ def test_empty_first_arg(self):
568
+ # first arg must have at least one value
569
+ with pytest.raises(ValueError, match=r'len\(a\)'):
570
+ convolution_matrix([], 4)
571
+
572
+ def test_bad_mode(self):
573
+ # mode must be in ('full', 'valid', 'same')
574
+ with pytest.raises(ValueError, match='mode.*must be one of'):
575
+ convolution_matrix((1, 1), 4, mode='invalid argument')
576
+
577
+ @pytest.mark.parametrize('cpx', [False, True])
578
+ @pytest.mark.parametrize('na', [1, 2, 9])
579
+ @pytest.mark.parametrize('nv', [1, 2, 9])
580
+ @pytest.mark.parametrize('mode', [None, 'full', 'valid', 'same'])
581
+ def test_against_numpy_convolve(self, cpx, na, nv, mode):
582
+ a = self.create_vector(na, cpx)
583
+ v = self.create_vector(nv, cpx)
584
+ if mode is None:
585
+ y1 = np.convolve(v, a)
586
+ A = convolution_matrix(a, nv)
587
+ else:
588
+ y1 = np.convolve(v, a, mode)
589
+ A = convolution_matrix(a, nv, mode)
590
+ y2 = A @ v
591
+ assert_array_almost_equal(y1, y2)
592
+
593
+
594
+ @pytest.mark.fail_slow(5) # `leslie` has an import in the function
595
+ @pytest.mark.parametrize('f, args', [(circulant, ()),
596
+ (companion, ()),
597
+ (convolution_matrix, (5, 'same')),
598
+ (fiedler, ()),
599
+ (fiedler_companion, ()),
600
+ (hankel, (np.arange(9),)),
601
+ (leslie, (np.arange(9),)),
602
+ (toeplitz, (np.arange(9),)),
603
+ ])
604
+ def test_batch(f, args):
605
+ rng = np.random.default_rng(283592436523456)
606
+ batch_shape = (2, 3)
607
+ m = 10
608
+ A = rng.random(batch_shape + (m,))
609
+
610
+ if f in {hankel}:
611
+ message = "Beginning in SciPy 1.19, multidimensional input will be..."
612
+ with pytest.warns(FutureWarning, match=message):
613
+ f(A, *args)
614
+ return
615
+
616
+ res = f(A, *args)
617
+ ref = np.asarray([f(a, *args) for a in A.reshape(-1, m)])
618
+ ref = ref.reshape(A.shape[:-1] + ref.shape[-2:])
619
+ assert_allclose(res, ref)
.venv/lib/python3.12/site-packages/scipy/misc/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import warnings
2
+ warnings.warn(
3
+ "scipy.misc is deprecated and will be removed in 2.0.0",
4
+ DeprecationWarning,
5
+ stacklevel=2
6
+ )
.venv/lib/python3.12/site-packages/scipy/misc/common.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import warnings
2
+ warnings.warn(
3
+ "scipy.misc.common is deprecated and will be removed in 2.0.0",
4
+ DeprecationWarning,
5
+ stacklevel=2
6
+ )
.venv/lib/python3.12/site-packages/scipy/misc/doccer.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import warnings
2
+ warnings.warn(
3
+ "scipy.misc.doccer is deprecated and will be removed in 2.0.0",
4
+ DeprecationWarning,
5
+ stacklevel=2
6
+ )
.venv/lib/python3.12/site-packages/scipy/ndimage/__init__.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ =========================================================
3
+ Multidimensional image processing (:mod:`scipy.ndimage`)
4
+ =========================================================
5
+
6
+ .. currentmodule:: scipy.ndimage
7
+
8
+ This package contains various functions for multidimensional image
9
+ processing.
10
+
11
+
12
+ Filters
13
+ =======
14
+
15
+ .. autosummary::
16
+ :toctree: generated/
17
+
18
+ convolve - Multidimensional convolution
19
+ convolve1d - 1-D convolution along the given axis
20
+ correlate - Multidimensional correlation
21
+ correlate1d - 1-D correlation along the given axis
22
+ gaussian_filter
23
+ gaussian_filter1d
24
+ gaussian_gradient_magnitude
25
+ gaussian_laplace
26
+ generic_filter - Multidimensional filter using a given function
27
+ generic_filter1d - 1-D generic filter along the given axis
28
+ generic_gradient_magnitude
29
+ generic_laplace
30
+ laplace - N-D Laplace filter based on approximate second derivatives
31
+ maximum_filter
32
+ maximum_filter1d
33
+ median_filter - Calculates a multidimensional median filter
34
+ minimum_filter
35
+ minimum_filter1d
36
+ percentile_filter - Calculates a multidimensional percentile filter
37
+ prewitt
38
+ rank_filter - Calculates a multidimensional rank filter
39
+ sobel
40
+ uniform_filter - Multidimensional uniform filter
41
+ uniform_filter1d - 1-D uniform filter along the given axis
42
+ vectorized_filter
43
+
44
+ Fourier filters
45
+ ===============
46
+
47
+ .. autosummary::
48
+ :toctree: generated/
49
+
50
+ fourier_ellipsoid
51
+ fourier_gaussian
52
+ fourier_shift
53
+ fourier_uniform
54
+
55
+ Interpolation
56
+ =============
57
+
58
+ .. autosummary::
59
+ :toctree: generated/
60
+
61
+ affine_transform - Apply an affine transformation
62
+ geometric_transform - Apply an arbitrary geometric transform
63
+ map_coordinates - Map input array to new coordinates by interpolation
64
+ rotate - Rotate an array
65
+ shift - Shift an array
66
+ spline_filter
67
+ spline_filter1d
68
+ zoom - Zoom an array
69
+
70
+ Measurements
71
+ ============
72
+
73
+ .. autosummary::
74
+ :toctree: generated/
75
+
76
+ center_of_mass - The center of mass of the values of an array at labels
77
+ extrema - Min's and max's of an array at labels, with their positions
78
+ find_objects - Find objects in a labeled array
79
+ histogram - Histogram of the values of an array, optionally at labels
80
+ label - Label features in an array
81
+ labeled_comprehension
82
+ maximum
83
+ maximum_position
84
+ mean - Mean of the values of an array at labels
85
+ median
86
+ minimum
87
+ minimum_position
88
+ standard_deviation - Standard deviation of an N-D image array
89
+ sum_labels - Sum of the values of the array
90
+ value_indices - Find indices of each distinct value in given array
91
+ variance - Variance of the values of an N-D image array
92
+ watershed_ift
93
+
94
+ Morphology
95
+ ==========
96
+
97
+ .. autosummary::
98
+ :toctree: generated/
99
+
100
+ binary_closing
101
+ binary_dilation
102
+ binary_erosion
103
+ binary_fill_holes
104
+ binary_hit_or_miss
105
+ binary_opening
106
+ binary_propagation
107
+ black_tophat
108
+ distance_transform_bf
109
+ distance_transform_cdt
110
+ distance_transform_edt
111
+ generate_binary_structure
112
+ grey_closing
113
+ grey_dilation
114
+ grey_erosion
115
+ grey_opening
116
+ iterate_structure
117
+ morphological_gradient
118
+ morphological_laplace
119
+ white_tophat
120
+
121
+ """
122
+
123
+ # Copyright (C) 2003-2005 Peter J. Verveer
124
+ #
125
+ # Redistribution and use in source and binary forms, with or without
126
+ # modification, are permitted provided that the following conditions
127
+ # are met:
128
+ #
129
+ # 1. Redistributions of source code must retain the above copyright
130
+ # notice, this list of conditions and the following disclaimer.
131
+ #
132
+ # 2. Redistributions in binary form must reproduce the above
133
+ # copyright notice, this list of conditions and the following
134
+ # disclaimer in the documentation and/or other materials provided
135
+ # with the distribution.
136
+ #
137
+ # 3. The name of the author may not be used to endorse or promote
138
+ # products derived from this software without specific prior
139
+ # written permission.
140
+ #
141
+ # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
142
+ # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
143
+ # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
144
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
145
+ # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
146
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
147
+ # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
148
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
149
+ # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
150
+ # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
151
+ # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
152
+
153
+ # bring in the public functionality from private namespaces
154
+
155
+ # mypy: ignore-errors
156
+
157
+ from ._support_alternative_backends import *
158
+
159
+ # adjust __all__ and do not leak implementation details
160
+ from . import _support_alternative_backends
161
+ __all__ = _support_alternative_backends.__all__
162
+ del _support_alternative_backends, _ndimage_api, _delegators # noqa: F821 # pyrefly:ignore[unbound-name]
163
+
164
+
165
+ # Deprecated namespaces, to be removed in v2.0.0
166
+ from . import filters
167
+ from . import fourier
168
+ from . import interpolation
169
+ from . import measurements
170
+ from . import morphology
171
+
172
+ from scipy._lib._testutils import PytestTester
173
+ test = PytestTester(__name__)
174
+ del PytestTester
.venv/lib/python3.12/site-packages/scipy/ndimage/_ctest.cpython-312-x86_64-linux-gnu.so ADDED
Binary file (17 kB). View file
 
.venv/lib/python3.12/site-packages/scipy/ndimage/_cytest.cpython-312-x86_64-linux-gnu.so ADDED
Binary file (94.4 kB). View file
 
.venv/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/lib/python3.12/site-packages/scipy/ndimage/_filters.py ADDED
@@ -0,0 +1,2446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Returned array of same shape as `input`.
717
+
718
+ Notes
719
+ -----
720
+ The Gaussian kernel will have size ``2*radius + 1`` along each axis. If
721
+ `radius` is None, a default ``radius = round(truncate * sigma)`` will be
722
+ used.
723
+
724
+ Examples
725
+ --------
726
+ >>> from scipy.ndimage import gaussian_filter1d
727
+ >>> import numpy as np
728
+ >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 1)
729
+ array([ 1.42704095, 2.06782203, 3. , 3.93217797, 4.57295905])
730
+ >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 4)
731
+ array([ 2.91948343, 2.95023502, 3. , 3.04976498, 3.08051657])
732
+ >>> import matplotlib.pyplot as plt
733
+ >>> rng = np.random.default_rng()
734
+ >>> x = rng.standard_normal(101).cumsum()
735
+ >>> y3 = gaussian_filter1d(x, 3)
736
+ >>> y6 = gaussian_filter1d(x, 6)
737
+ >>> plt.plot(x, 'k', label='original data')
738
+ >>> plt.plot(y3, '--', label='filtered, sigma=3')
739
+ >>> plt.plot(y6, ':', label='filtered, sigma=6')
740
+ >>> plt.legend()
741
+ >>> plt.grid()
742
+ >>> plt.show()
743
+
744
+ """
745
+ sd = float(sigma)
746
+ # make the radius of the filter equal to truncate standard deviations
747
+ lw = int(truncate * sd + 0.5)
748
+ if radius is not None:
749
+ lw = radius
750
+ if not isinstance(lw, numbers.Integral) or lw < 0:
751
+ raise ValueError('Radius must be a nonnegative integer.')
752
+ # Since we are calling correlate, not convolve, revert the kernel
753
+ weights = _gaussian_kernel1d(sigma, order, lw)[::-1]
754
+ return correlate1d(input, weights, axis, output, mode, cval, 0)
755
+
756
+
757
+ @_ni_docstrings.docfiller
758
+ def gaussian_filter(input, sigma, order=0, output=None,
759
+ mode="reflect", cval=0.0, truncate=4.0, *, radius=None,
760
+ axes=None):
761
+ """Multidimensional Gaussian filter.
762
+
763
+ Parameters
764
+ ----------
765
+ %(input)s
766
+ sigma : scalar or sequence of scalars
767
+ Standard deviation for Gaussian kernel. The standard
768
+ deviations of the Gaussian filter are given for each axis as a
769
+ sequence, or as a single number, in which case it is equal for
770
+ all axes.
771
+ order : int or sequence of ints, optional
772
+ The order of the filter along each axis is given as a sequence
773
+ of integers, or as a single number. An order of 0 corresponds
774
+ to convolution with a Gaussian kernel. A positive order
775
+ corresponds to convolution with that derivative of a Gaussian.
776
+ %(output)s
777
+ %(mode_multiple)s
778
+ %(cval)s
779
+ truncate : float, optional
780
+ Truncate the filter at this many standard deviations.
781
+ Default is 4.0.
782
+ radius : None or int or sequence of ints, optional
783
+ Radius of the Gaussian kernel. The radius are given for each axis
784
+ as a sequence, or as a single number, in which case it is equal
785
+ for all axes. If specified, the size of the kernel along each axis
786
+ will be ``2*radius + 1``, and `truncate` is ignored.
787
+ Default is None.
788
+ axes : tuple of int or None, optional
789
+ If None, `input` is filtered along all axes. Otherwise,
790
+ `input` is filtered along the specified axes. When `axes` is
791
+ specified, any tuples used for `sigma`, `order`, `mode` and/or `radius`
792
+ must match the length of `axes`. The ith entry in any of these tuples
793
+ corresponds to the ith entry in `axes`.
794
+
795
+ Returns
796
+ -------
797
+ gaussian_filter : ndarray
798
+ Returned array of same shape as `input`.
799
+
800
+ Notes
801
+ -----
802
+ The multidimensional filter is implemented as a sequence of
803
+ 1-D convolution filters. The intermediate arrays are
804
+ stored in the same data type as the output. Therefore, for output
805
+ types with a limited precision, the results may be imprecise
806
+ because intermediate results may be stored with insufficient
807
+ precision.
808
+
809
+ The Gaussian kernel will have size ``2*radius + 1`` along each axis. If
810
+ `radius` is None, the default ``radius = round(truncate * sigma)`` will be
811
+ used.
812
+
813
+ Examples
814
+ --------
815
+ >>> from scipy.ndimage import gaussian_filter
816
+ >>> import numpy as np
817
+ >>> a = np.arange(50, step=2).reshape((5,5))
818
+ >>> a
819
+ array([[ 0, 2, 4, 6, 8],
820
+ [10, 12, 14, 16, 18],
821
+ [20, 22, 24, 26, 28],
822
+ [30, 32, 34, 36, 38],
823
+ [40, 42, 44, 46, 48]])
824
+ >>> gaussian_filter(a, sigma=1)
825
+ array([[ 4, 6, 8, 9, 11],
826
+ [10, 12, 14, 15, 17],
827
+ [20, 22, 24, 25, 27],
828
+ [29, 31, 33, 34, 36],
829
+ [35, 37, 39, 40, 42]])
830
+
831
+ >>> from scipy import datasets
832
+ >>> import matplotlib.pyplot as plt
833
+ >>> fig = plt.figure()
834
+ >>> plt.gray() # show the filtered result in grayscale
835
+ >>> ax1 = fig.add_subplot(121) # left side
836
+ >>> ax2 = fig.add_subplot(122) # right side
837
+ >>> ascent = datasets.ascent()
838
+ >>> result = gaussian_filter(ascent, sigma=5)
839
+ >>> ax1.imshow(ascent)
840
+ >>> ax2.imshow(result)
841
+ >>> plt.show()
842
+ """
843
+ input = np.asarray(input)
844
+ output = _ni_support._get_output(output, input)
845
+
846
+ axes = _ni_support._check_axes(axes, input.ndim)
847
+ num_axes = len(axes)
848
+ orders = _ni_support._normalize_sequence(order, num_axes)
849
+ sigmas = _ni_support._normalize_sequence(sigma, num_axes)
850
+ modes = _ni_support._normalize_sequence(mode, num_axes)
851
+ radiuses = _ni_support._normalize_sequence(radius, num_axes)
852
+ axes = [(axes[ii], sigmas[ii], orders[ii], modes[ii], radiuses[ii])
853
+ for ii in range(num_axes) if sigmas[ii] > 1e-15]
854
+ if len(axes) > 0:
855
+ for axis, sigma, order, mode, radius in axes:
856
+ gaussian_filter1d(input, sigma, axis, order, output,
857
+ mode, cval, truncate, radius=radius)
858
+ input = output
859
+ else:
860
+ output[...] = input[...]
861
+ return output
862
+
863
+
864
+ @_ni_docstrings.docfiller
865
+ def prewitt(input, axis=-1, output=None, mode="reflect", cval=0.0):
866
+ """Calculate a Prewitt filter.
867
+
868
+ Parameters
869
+ ----------
870
+ %(input)s
871
+ %(axis)s
872
+ %(output)s
873
+ %(mode_multiple)s
874
+ %(cval)s
875
+
876
+ Returns
877
+ -------
878
+ prewitt : ndarray
879
+ Filtered array. Has the same shape as `input`.
880
+
881
+ See Also
882
+ --------
883
+ sobel: Sobel filter
884
+
885
+ Notes
886
+ -----
887
+ This function computes the one-dimensional Prewitt filter.
888
+ Horizontal edges are emphasised with the horizontal transform (axis=0),
889
+ vertical edges with the vertical transform (axis=1), and so on for higher
890
+ dimensions. These can be combined to give the magnitude.
891
+
892
+ Examples
893
+ --------
894
+ >>> from scipy import ndimage, datasets
895
+ >>> import matplotlib.pyplot as plt
896
+ >>> import numpy as np
897
+ >>> ascent = datasets.ascent()
898
+ >>> prewitt_h = ndimage.prewitt(ascent, axis=0)
899
+ >>> prewitt_v = ndimage.prewitt(ascent, axis=1)
900
+ >>> magnitude = np.sqrt(prewitt_h ** 2 + prewitt_v ** 2)
901
+ >>> magnitude *= 255 / np.max(magnitude) # Normalization
902
+ >>> fig, axes = plt.subplots(2, 2, figsize = (8, 8))
903
+ >>> plt.gray()
904
+ >>> axes[0, 0].imshow(ascent)
905
+ >>> axes[0, 1].imshow(prewitt_h)
906
+ >>> axes[1, 0].imshow(prewitt_v)
907
+ >>> axes[1, 1].imshow(magnitude)
908
+ >>> titles = ["original", "horizontal", "vertical", "magnitude"]
909
+ >>> for i, ax in enumerate(axes.ravel()):
910
+ ... ax.set_title(titles[i])
911
+ ... ax.axis("off")
912
+ >>> plt.show()
913
+
914
+ """
915
+ input = np.asarray(input)
916
+ axis = normalize_axis_index(axis, input.ndim)
917
+ output = _ni_support._get_output(output, input)
918
+ modes = _ni_support._normalize_sequence(mode, input.ndim)
919
+ correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0)
920
+ axes = [ii for ii in range(input.ndim) if ii != axis]
921
+ for ii in axes:
922
+ correlate1d(output, [1, 1, 1], ii, output, modes[ii], cval, 0,)
923
+ return output
924
+
925
+
926
+ @_ni_docstrings.docfiller
927
+ def sobel(input, axis=-1, output=None, mode="reflect", cval=0.0):
928
+ """Calculate a Sobel filter.
929
+
930
+ Parameters
931
+ ----------
932
+ %(input)s
933
+ %(axis)s
934
+ %(output)s
935
+ %(mode_multiple)s
936
+ %(cval)s
937
+
938
+ Returns
939
+ -------
940
+ sobel : ndarray
941
+ Filtered array. Has the same shape as `input`.
942
+
943
+ Notes
944
+ -----
945
+ This function computes the axis-specific Sobel gradient.
946
+ The horizontal edges can be emphasised with the horizontal transform (axis=0),
947
+ the vertical edges with the vertical transform (axis=1) and so on for higher
948
+ dimensions. These can be combined to give the magnitude.
949
+
950
+ Examples
951
+ --------
952
+ >>> from scipy import ndimage, datasets
953
+ >>> import matplotlib.pyplot as plt
954
+ >>> import numpy as np
955
+ >>> ascent = datasets.ascent().astype('int32')
956
+ >>> sobel_h = ndimage.sobel(ascent, 0) # horizontal gradient
957
+ >>> sobel_v = ndimage.sobel(ascent, 1) # vertical gradient
958
+ >>> magnitude = np.sqrt(sobel_h**2 + sobel_v**2)
959
+ >>> magnitude *= 255.0 / np.max(magnitude) # normalization
960
+ >>> fig, axs = plt.subplots(2, 2, figsize=(8, 8))
961
+ >>> plt.gray() # show the filtered result in grayscale
962
+ >>> axs[0, 0].imshow(ascent)
963
+ >>> axs[0, 1].imshow(sobel_h)
964
+ >>> axs[1, 0].imshow(sobel_v)
965
+ >>> axs[1, 1].imshow(magnitude)
966
+ >>> titles = ["original", "horizontal", "vertical", "magnitude"]
967
+ >>> for i, ax in enumerate(axs.ravel()):
968
+ ... ax.set_title(titles[i])
969
+ ... ax.axis("off")
970
+ >>> plt.show()
971
+
972
+ """
973
+ input = np.asarray(input)
974
+ axis = normalize_axis_index(axis, input.ndim)
975
+ output = _ni_support._get_output(output, input)
976
+ modes = _ni_support._normalize_sequence(mode, input.ndim)
977
+ correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0)
978
+ axes = [ii for ii in range(input.ndim) if ii != axis]
979
+ for ii in axes:
980
+ correlate1d(output, [1, 2, 1], ii, output, modes[ii], cval, 0)
981
+ return output
982
+
983
+
984
+ @_ni_docstrings.docfiller
985
+ def generic_laplace(input, derivative2, output=None, mode="reflect",
986
+ cval=0.0,
987
+ extra_arguments=(),
988
+ extra_keywords=None,
989
+ *, axes=None):
990
+ """
991
+ N-D Laplace filter using a provided second derivative function.
992
+
993
+ Parameters
994
+ ----------
995
+ %(input)s
996
+ derivative2 : callable
997
+ Callable with the following signature::
998
+
999
+ derivative2(input, axis, output, mode, cval,
1000
+ *extra_arguments, **extra_keywords)
1001
+
1002
+ See `extra_arguments`, `extra_keywords` below.
1003
+ %(output)s
1004
+ %(mode_multiple)s
1005
+ %(cval)s
1006
+ %(extra_arguments)s
1007
+ %(extra_keywords)s
1008
+ axes : tuple of int or None
1009
+ The axes over which to apply the filter. If a `mode` tuple is
1010
+ provided, its length must match the number of axes.
1011
+
1012
+ Returns
1013
+ -------
1014
+ generic_laplace : ndarray
1015
+ Filtered array. Has the same shape as `input`.
1016
+
1017
+ """
1018
+ if extra_keywords is None:
1019
+ extra_keywords = {}
1020
+ input = np.asarray(input)
1021
+ output = _ni_support._get_output(output, input)
1022
+ axes = _ni_support._check_axes(axes, input.ndim)
1023
+ if len(axes) > 0:
1024
+ modes = _ni_support._normalize_sequence(mode, len(axes))
1025
+ derivative2(input, axes[0], output, modes[0], cval,
1026
+ *extra_arguments, **extra_keywords)
1027
+ for ii in range(1, len(axes)):
1028
+ tmp = derivative2(input, axes[ii], output.dtype, modes[ii], cval,
1029
+ *extra_arguments, **extra_keywords)
1030
+ output += tmp
1031
+ else:
1032
+ output[...] = input[...]
1033
+ return output
1034
+
1035
+
1036
+ @_ni_docstrings.docfiller
1037
+ def laplace(input, output=None, mode="reflect", cval=0.0, *, axes=None):
1038
+ """N-D Laplace filter based on approximate second derivatives.
1039
+
1040
+ Parameters
1041
+ ----------
1042
+ %(input)s
1043
+ %(output)s
1044
+ %(mode_multiple)s
1045
+ %(cval)s
1046
+ axes : tuple of int or None
1047
+ The axes over which to apply the filter. If a `mode` tuple is
1048
+ provided, its length must match the number of axes.
1049
+
1050
+ Returns
1051
+ -------
1052
+ laplace : ndarray
1053
+ Filtered array. Has the same shape as `input`.
1054
+
1055
+ Examples
1056
+ --------
1057
+ >>> from scipy import ndimage, datasets
1058
+ >>> import matplotlib.pyplot as plt
1059
+ >>> fig = plt.figure()
1060
+ >>> plt.gray() # show the filtered result in grayscale
1061
+ >>> ax1 = fig.add_subplot(121) # left side
1062
+ >>> ax2 = fig.add_subplot(122) # right side
1063
+ >>> ascent = datasets.ascent()
1064
+ >>> result = ndimage.laplace(ascent)
1065
+ >>> ax1.imshow(ascent)
1066
+ >>> ax2.imshow(result)
1067
+ >>> plt.show()
1068
+ """
1069
+ def derivative2(input, axis, output, mode, cval):
1070
+ return correlate1d(input, [1, -2, 1], axis, output, mode, cval, 0)
1071
+ return generic_laplace(input, derivative2, output, mode, cval, axes=axes)
1072
+
1073
+
1074
+ @_ni_docstrings.docfiller
1075
+ def gaussian_laplace(input, sigma, output=None, mode="reflect",
1076
+ cval=0.0, *, axes=None, **kwargs):
1077
+ """Multidimensional Laplace filter using Gaussian second derivatives.
1078
+
1079
+ Parameters
1080
+ ----------
1081
+ %(input)s
1082
+ sigma : scalar or sequence of scalars
1083
+ The standard deviations of the Gaussian filter are given for
1084
+ each axis as a sequence, or as a single number, in which case
1085
+ it is equal for all axes.
1086
+ %(output)s
1087
+ %(mode_multiple)s
1088
+ %(cval)s
1089
+ axes : tuple of int or None
1090
+ The axes over which to apply the filter. If `sigma` or `mode` tuples
1091
+ are provided, their length must match the number of axes.
1092
+ **kwargs
1093
+ Extra keyword arguments will be passed to `gaussian_filter`.
1094
+
1095
+ Returns
1096
+ -------
1097
+ gaussian_laplace : ndarray
1098
+ Filtered array. Has the same shape as `input`.
1099
+
1100
+ Examples
1101
+ --------
1102
+ >>> from scipy import ndimage, datasets
1103
+ >>> import matplotlib.pyplot as plt
1104
+ >>> ascent = datasets.ascent()
1105
+
1106
+ >>> fig = plt.figure()
1107
+ >>> plt.gray() # show the filtered result in grayscale
1108
+ >>> ax1 = fig.add_subplot(121) # left side
1109
+ >>> ax2 = fig.add_subplot(122) # right side
1110
+
1111
+ >>> result = ndimage.gaussian_laplace(ascent, sigma=1)
1112
+ >>> ax1.imshow(result)
1113
+
1114
+ >>> result = ndimage.gaussian_laplace(ascent, sigma=3)
1115
+ >>> ax2.imshow(result)
1116
+ >>> plt.show()
1117
+ """
1118
+ input = np.asarray(input)
1119
+
1120
+ def derivative2(input, axis, output, mode, cval, sigma, **kwargs):
1121
+ order = [0] * input.ndim
1122
+ order[axis] = 2
1123
+ return gaussian_filter(input, sigma, order, output, mode, cval,
1124
+ **kwargs)
1125
+
1126
+ axes = _ni_support._check_axes(axes, input.ndim)
1127
+ num_axes = len(axes)
1128
+ sigma = _ni_support._normalize_sequence(sigma, num_axes)
1129
+ if num_axes < input.ndim:
1130
+ # set sigma = 0 for any axes not being filtered
1131
+ sigma_temp = [0,] * input.ndim
1132
+ for s, ax in zip(sigma, axes):
1133
+ sigma_temp[ax] = s
1134
+ sigma = sigma_temp
1135
+
1136
+ return generic_laplace(input, derivative2, output, mode, cval,
1137
+ extra_arguments=(sigma,),
1138
+ extra_keywords=kwargs,
1139
+ axes=axes)
1140
+
1141
+
1142
+ @_ni_docstrings.docfiller
1143
+ def generic_gradient_magnitude(input, derivative, output=None,
1144
+ mode="reflect", cval=0.0,
1145
+ extra_arguments=(), extra_keywords=None,
1146
+ *, axes=None):
1147
+ """Gradient magnitude using a provided gradient function.
1148
+
1149
+ Parameters
1150
+ ----------
1151
+ %(input)s
1152
+ derivative : callable
1153
+ Callable with the following signature::
1154
+
1155
+ derivative(input, axis, output, mode, cval,
1156
+ *extra_arguments, **extra_keywords)
1157
+
1158
+ See `extra_arguments`, `extra_keywords` below.
1159
+ `derivative` can assume that `input` and `output` are ndarrays.
1160
+ Note that the output from `derivative` is modified inplace;
1161
+ be careful to copy important inputs before returning them.
1162
+ %(output)s
1163
+ %(mode_multiple)s
1164
+ %(cval)s
1165
+ %(extra_arguments)s
1166
+ %(extra_keywords)s
1167
+ axes : tuple of int or None
1168
+ The axes over which to apply the filter. If a `mode` tuple is
1169
+ provided, its length must match the number of axes.
1170
+
1171
+ Returns
1172
+ -------
1173
+ generic_gradient_magnitude : ndarray
1174
+ Filtered array. Has the same shape as `input`.
1175
+
1176
+ """
1177
+ if extra_keywords is None:
1178
+ extra_keywords = {}
1179
+ input = np.asarray(input)
1180
+ output = _ni_support._get_output(output, input)
1181
+ axes = _ni_support._check_axes(axes, input.ndim)
1182
+ if len(axes) > 0:
1183
+ modes = _ni_support._normalize_sequence(mode, len(axes))
1184
+ derivative(input, axes[0], output, modes[0], cval,
1185
+ *extra_arguments, **extra_keywords)
1186
+ np.multiply(output, output, output)
1187
+ for ii in range(1, len(axes)):
1188
+ tmp = derivative(input, axes[ii], output.dtype, modes[ii], cval,
1189
+ *extra_arguments, **extra_keywords)
1190
+ np.multiply(tmp, tmp, tmp)
1191
+ output += tmp
1192
+ # This allows the sqrt to work with a different default casting
1193
+ np.sqrt(output, output, casting='unsafe')
1194
+ else:
1195
+ output[...] = input[...]
1196
+ return output
1197
+
1198
+
1199
+ @_ni_docstrings.docfiller
1200
+ def gaussian_gradient_magnitude(input, sigma, output=None,
1201
+ mode="reflect", cval=0.0, *, axes=None,
1202
+ **kwargs):
1203
+ """Multidimensional gradient magnitude using Gaussian derivatives.
1204
+
1205
+ Parameters
1206
+ ----------
1207
+ %(input)s
1208
+ sigma : scalar or sequence of scalars
1209
+ The standard deviations of the Gaussian filter are given for
1210
+ each axis as a sequence, or as a single number, in which case
1211
+ it is equal for all axes.
1212
+ %(output)s
1213
+ %(mode_multiple)s
1214
+ %(cval)s
1215
+ axes : tuple of int or None
1216
+ The axes over which to apply the filter. If `sigma` or `mode` tuples
1217
+ are provided, their length must match the number of axes.
1218
+ **kwargs
1219
+ Extra keyword arguments will be passed to `gaussian_filter`.
1220
+
1221
+ Returns
1222
+ -------
1223
+ gaussian_gradient_magnitude : ndarray
1224
+ Filtered array. Has the same shape as `input`.
1225
+
1226
+ Examples
1227
+ --------
1228
+ >>> from scipy import ndimage, datasets
1229
+ >>> import matplotlib.pyplot as plt
1230
+ >>> fig = plt.figure()
1231
+ >>> plt.gray() # show the filtered result in grayscale
1232
+ >>> ax1 = fig.add_subplot(121) # left side
1233
+ >>> ax2 = fig.add_subplot(122) # right side
1234
+ >>> ascent = datasets.ascent()
1235
+ >>> result = ndimage.gaussian_gradient_magnitude(ascent, sigma=5)
1236
+ >>> ax1.imshow(ascent)
1237
+ >>> ax2.imshow(result)
1238
+ >>> plt.show()
1239
+ """
1240
+ input = np.asarray(input)
1241
+
1242
+ def derivative(input, axis, output, mode, cval, sigma, **kwargs):
1243
+ order = [0] * input.ndim
1244
+ order[axis] = 1
1245
+ return gaussian_filter(input, sigma, order, output, mode,
1246
+ cval, **kwargs)
1247
+
1248
+ return generic_gradient_magnitude(input, derivative, output, mode,
1249
+ cval, extra_arguments=(sigma,),
1250
+ extra_keywords=kwargs, axes=axes)
1251
+
1252
+
1253
+ def _correlate_or_convolve(input, weights, output, mode, cval, origin,
1254
+ convolution, axes):
1255
+ input = np.asarray(input)
1256
+ weights = np.asarray(weights)
1257
+ complex_input = input.dtype.kind == 'c'
1258
+ complex_weights = weights.dtype.kind == 'c'
1259
+ if complex_input or complex_weights:
1260
+ if complex_weights and not convolution:
1261
+ # As for np.correlate, conjugate weights rather than input.
1262
+ weights = weights.conj()
1263
+ kwargs = dict(
1264
+ mode=mode, origin=origin, convolution=convolution, axes=axes
1265
+ )
1266
+ output = _ni_support._get_output(output, input, complex_output=True)
1267
+
1268
+ return _complex_via_real_components(_correlate_or_convolve, input,
1269
+ weights, output, cval, **kwargs)
1270
+
1271
+ axes = _ni_support._check_axes(axes, input.ndim)
1272
+ weights = np.asarray(weights, dtype=np.float64)
1273
+
1274
+ # expand weights and origins if num_axes < input.ndim
1275
+ weights = _expand_footprint(input.ndim, axes, weights, "weights")
1276
+ origins = _expand_origin(input.ndim, axes, origin)
1277
+
1278
+ wshape = [ii for ii in weights.shape if ii > 0]
1279
+ if len(wshape) != input.ndim:
1280
+ raise RuntimeError(f"weights.ndim ({len(wshape)}) must match "
1281
+ f"len(axes) ({len(axes)})")
1282
+ if convolution:
1283
+ weights = weights[tuple([slice(None, None, -1)] * weights.ndim)]
1284
+ for ii in range(len(origins)):
1285
+ origins[ii] = -origins[ii]
1286
+ if not weights.shape[ii] & 1:
1287
+ origins[ii] -= 1
1288
+ for origin, lenw in zip(origins, wshape):
1289
+ if _invalid_origin(origin, lenw):
1290
+ raise ValueError('Invalid origin; origin must satisfy '
1291
+ '-(weights.shape[k] // 2) <= origin[k] <= '
1292
+ '(weights.shape[k]-1) // 2')
1293
+
1294
+ if not weights.flags.contiguous:
1295
+ weights = weights.copy()
1296
+ output = _ni_support._get_output(output, input)
1297
+ temp_needed = np.may_share_memory(input, output)
1298
+ if temp_needed:
1299
+ # input and output arrays cannot share memory
1300
+ temp = output
1301
+ output = _ni_support._get_output(output.dtype, input)
1302
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
1303
+ raise RuntimeError("A sequence of modes is not supported")
1304
+ mode = _ni_support._extend_mode_to_code(mode)
1305
+ _nd_image.correlate(input, weights, output, mode, cval, origins)
1306
+ if temp_needed:
1307
+ temp[...] = output
1308
+ output = temp
1309
+ return output
1310
+
1311
+
1312
+ @_ni_docstrings.docfiller
1313
+ def correlate(input, weights, output=None, mode='reflect', cval=0.0,
1314
+ origin=0, *, axes=None):
1315
+ """
1316
+ Multidimensional correlation.
1317
+
1318
+ The array is correlated with the given kernel.
1319
+
1320
+ Parameters
1321
+ ----------
1322
+ %(input)s
1323
+ weights : ndarray
1324
+ array of weights, same number of dimensions as input
1325
+ %(output)s
1326
+ %(mode_reflect)s
1327
+ %(cval)s
1328
+ %(origin_multiple)s
1329
+ axes : tuple of int or None, optional
1330
+ If None, `input` is filtered along all axes. Otherwise,
1331
+ `input` is filtered along the specified axes. When `axes` is
1332
+ specified, any tuples used for `mode` or `origin` must match the length
1333
+ of `axes`. The ith entry in any of these tuples corresponds to the ith
1334
+ entry in `axes`.
1335
+
1336
+ Returns
1337
+ -------
1338
+ result : ndarray
1339
+ The result of correlation of `input` with `weights`.
1340
+
1341
+ See Also
1342
+ --------
1343
+ convolve : Convolve an image with a kernel.
1344
+
1345
+ Examples
1346
+ --------
1347
+ Correlation is the process of moving a filter mask often referred to
1348
+ as kernel over the image and computing the sum of products at each location.
1349
+
1350
+ >>> from scipy.ndimage import correlate
1351
+ >>> import numpy as np
1352
+ >>> input_img = np.arange(25).reshape(5,5)
1353
+ >>> print(input_img)
1354
+ [[ 0 1 2 3 4]
1355
+ [ 5 6 7 8 9]
1356
+ [10 11 12 13 14]
1357
+ [15 16 17 18 19]
1358
+ [20 21 22 23 24]]
1359
+
1360
+ Define a kernel (weights) for correlation. In this example, it is for sum of
1361
+ center and up, down, left and right next elements.
1362
+
1363
+ >>> weights = [[0, 1, 0],
1364
+ ... [1, 1, 1],
1365
+ ... [0, 1, 0]]
1366
+
1367
+ We can calculate a correlation result:
1368
+ For example, element ``[2,2]`` is ``7 + 11 + 12 + 13 + 17 = 60``.
1369
+
1370
+ >>> correlate(input_img, weights)
1371
+ array([[ 6, 10, 15, 20, 24],
1372
+ [ 26, 30, 35, 40, 44],
1373
+ [ 51, 55, 60, 65, 69],
1374
+ [ 76, 80, 85, 90, 94],
1375
+ [ 96, 100, 105, 110, 114]])
1376
+
1377
+ """
1378
+ return _correlate_or_convolve(input, weights, output, mode, cval,
1379
+ origin, False, axes)
1380
+
1381
+
1382
+ @_ni_docstrings.docfiller
1383
+ def convolve(input, weights, output=None, mode='reflect', cval=0.0,
1384
+ origin=0, *, axes=None):
1385
+ """
1386
+ Multidimensional convolution.
1387
+
1388
+ The array is convolved with the given kernel.
1389
+
1390
+ Parameters
1391
+ ----------
1392
+ %(input)s
1393
+ weights : array_like
1394
+ Array of weights, same number of dimensions as input
1395
+ %(output)s
1396
+ %(mode_reflect)s
1397
+ cval : scalar, optional
1398
+ Value to fill past edges of input if `mode` is 'constant'. Default
1399
+ is 0.0
1400
+ origin : int or sequence, optional
1401
+ Controls the placement of the filter on the input array's pixels.
1402
+ A value of 0 (the default) centers the filter over the pixel, with
1403
+ positive values shifting the filter to the right, and negative ones
1404
+ to the left. By passing a sequence of origins with length equal to
1405
+ the number of dimensions of the input array, different shifts can
1406
+ be specified along each axis.
1407
+ axes : tuple of int or None, optional
1408
+ If None, `input` is filtered along all axes. Otherwise,
1409
+ `input` is filtered along the specified axes. When `axes` is
1410
+ specified, any tuples used for `mode` or `origin` must match the length
1411
+ of `axes`. The ith entry in any of these tuples corresponds to the ith
1412
+ entry in `axes`.
1413
+
1414
+ Returns
1415
+ -------
1416
+ result : ndarray
1417
+ The result of convolution of `input` with `weights`.
1418
+
1419
+ See Also
1420
+ --------
1421
+ correlate : Correlate an image with a kernel.
1422
+
1423
+ Notes
1424
+ -----
1425
+ Each value in result is :math:`C_i = \\sum_j{I_{i+k-j} W_j}`, where
1426
+ W is the `weights` kernel,
1427
+ j is the N-D spatial index over :math:`W`,
1428
+ I is the `input` and k is the coordinate of the center of
1429
+ W, specified by `origin` in the input parameters.
1430
+
1431
+ Examples
1432
+ --------
1433
+ Perhaps the simplest case to understand is ``mode='constant', cval=0.0``,
1434
+ because in this case borders (i.e., where the `weights` kernel, centered
1435
+ on any one value, extends beyond an edge of `input`) are treated as zeros.
1436
+
1437
+ >>> import numpy as np
1438
+ >>> a = np.array([[1, 2, 0, 0],
1439
+ ... [5, 3, 0, 4],
1440
+ ... [0, 0, 0, 7],
1441
+ ... [9, 3, 0, 0]])
1442
+ >>> k = np.array([[1,1,1],[1,1,0],[1,0,0]])
1443
+ >>> from scipy import ndimage
1444
+ >>> ndimage.convolve(a, k, mode='constant', cval=0.0)
1445
+ array([[11, 10, 7, 4],
1446
+ [10, 3, 11, 11],
1447
+ [15, 12, 14, 7],
1448
+ [12, 3, 7, 0]])
1449
+
1450
+ Setting ``cval=1.0`` is equivalent to padding the outer edge of `input`
1451
+ with 1.0's (and then extracting only the original region of the result).
1452
+
1453
+ >>> ndimage.convolve(a, k, mode='constant', cval=1.0)
1454
+ array([[13, 11, 8, 7],
1455
+ [11, 3, 11, 14],
1456
+ [16, 12, 14, 10],
1457
+ [15, 6, 10, 5]])
1458
+
1459
+ With ``mode='reflect'`` (the default), outer values are reflected at the
1460
+ edge of `input` to fill in missing values.
1461
+
1462
+ >>> b = np.array([[2, 0, 0],
1463
+ ... [1, 0, 0],
1464
+ ... [0, 0, 0]])
1465
+ >>> k = np.array([[0,1,0], [0,1,0], [0,1,0]])
1466
+ >>> ndimage.convolve(b, k, mode='reflect')
1467
+ array([[5, 0, 0],
1468
+ [3, 0, 0],
1469
+ [1, 0, 0]])
1470
+
1471
+ This includes diagonally at the corners.
1472
+
1473
+ >>> k = np.array([[1,0,0],[0,1,0],[0,0,1]])
1474
+ >>> ndimage.convolve(b, k)
1475
+ array([[4, 2, 0],
1476
+ [3, 2, 0],
1477
+ [1, 1, 0]])
1478
+
1479
+ With ``mode='nearest'``, the single nearest value in to an edge in
1480
+ `input` is repeated as many times as needed to match the overlapping
1481
+ `weights`.
1482
+
1483
+ >>> c = np.array([[2, 0, 1],
1484
+ ... [1, 0, 0],
1485
+ ... [0, 0, 0]])
1486
+ >>> k = np.array([[0, 1, 0],
1487
+ ... [0, 1, 0],
1488
+ ... [0, 1, 0],
1489
+ ... [0, 1, 0],
1490
+ ... [0, 1, 0]])
1491
+ >>> ndimage.convolve(c, k, mode='nearest')
1492
+ array([[7, 0, 3],
1493
+ [5, 0, 2],
1494
+ [3, 0, 1]])
1495
+
1496
+ """
1497
+ return _correlate_or_convolve(input, weights, output, mode, cval,
1498
+ origin, True, axes)
1499
+
1500
+
1501
+ @_ni_docstrings.docfiller
1502
+ def uniform_filter1d(input, size, axis=-1, output=None,
1503
+ mode="reflect", cval=0.0, origin=0):
1504
+ """Calculate a 1-D uniform filter along the given axis.
1505
+
1506
+ The lines of the array along the given axis are filtered with a
1507
+ uniform filter of given size.
1508
+
1509
+ Parameters
1510
+ ----------
1511
+ %(input)s
1512
+ size : int
1513
+ length of uniform filter
1514
+ %(axis)s
1515
+ %(output)s
1516
+ %(mode_reflect)s
1517
+ %(cval)s
1518
+ %(origin)s
1519
+
1520
+ Returns
1521
+ -------
1522
+ result : ndarray
1523
+ Filtered array. Has same shape as `input`.
1524
+
1525
+ Examples
1526
+ --------
1527
+ >>> from scipy.ndimage import uniform_filter1d
1528
+ >>> uniform_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
1529
+ array([4, 3, 4, 1, 4, 6, 6, 3])
1530
+ """
1531
+ input = np.asarray(input)
1532
+ axis = normalize_axis_index(axis, input.ndim)
1533
+ if size < 1:
1534
+ raise RuntimeError('incorrect filter size')
1535
+ complex_output = input.dtype.kind == 'c'
1536
+ output = _ni_support._get_output(output, input,
1537
+ complex_output=complex_output)
1538
+ if (size // 2 + origin < 0) or (size // 2 + origin >= size):
1539
+ raise ValueError('invalid origin')
1540
+ mode = _ni_support._extend_mode_to_code(mode)
1541
+ if not complex_output:
1542
+ _nd_image.uniform_filter1d(input, size, axis, output, mode, cval,
1543
+ origin)
1544
+ else:
1545
+ _nd_image.uniform_filter1d(input.real, size, axis, output.real, mode,
1546
+ np.real(cval), origin)
1547
+ _nd_image.uniform_filter1d(input.imag, size, axis, output.imag, mode,
1548
+ np.imag(cval), origin)
1549
+ return output
1550
+
1551
+
1552
+ @_ni_docstrings.docfiller
1553
+ def uniform_filter(input, size=3, output=None, mode="reflect",
1554
+ cval=0.0, origin=0, *, axes=None):
1555
+ """Multidimensional uniform filter.
1556
+
1557
+ Parameters
1558
+ ----------
1559
+ %(input)s
1560
+ size : int or sequence of ints, optional
1561
+ The sizes of the uniform filter are given for each axis as a
1562
+ sequence, or as a single number, in which case the size is
1563
+ equal for all axes.
1564
+ %(output)s
1565
+ %(mode_multiple)s
1566
+ %(cval)s
1567
+ %(origin_multiple)s
1568
+ axes : tuple of int or None, optional
1569
+ If None, `input` is filtered along all axes. Otherwise,
1570
+ `input` is filtered along the specified axes. When `axes` is
1571
+ specified, any tuples used for `size`, `origin`, and/or `mode`
1572
+ must match the length of `axes`. The ith entry in any of these tuples
1573
+ corresponds to the ith entry in `axes`.
1574
+
1575
+ Returns
1576
+ -------
1577
+ uniform_filter : ndarray
1578
+ Filtered array. Has the same shape as `input`.
1579
+
1580
+ Notes
1581
+ -----
1582
+ The multidimensional filter is implemented as a sequence of
1583
+ 1-D uniform filters. The intermediate arrays are stored
1584
+ in the same data type as the output. Therefore, for output types
1585
+ with a limited precision, the results may be imprecise because
1586
+ intermediate results may be stored with insufficient precision.
1587
+
1588
+ %(nan)s
1589
+
1590
+ Examples
1591
+ --------
1592
+ >>> from scipy import ndimage, datasets
1593
+ >>> import matplotlib.pyplot as plt
1594
+ >>> fig = plt.figure()
1595
+ >>> plt.gray() # show the filtered result in grayscale
1596
+ >>> ax1 = fig.add_subplot(121) # left side
1597
+ >>> ax2 = fig.add_subplot(122) # right side
1598
+ >>> ascent = datasets.ascent()
1599
+ >>> result = ndimage.uniform_filter(ascent, size=20)
1600
+ >>> ax1.imshow(ascent)
1601
+ >>> ax2.imshow(result)
1602
+ >>> plt.show()
1603
+ """
1604
+ input = np.asarray(input)
1605
+ output = _ni_support._get_output(output, input,
1606
+ complex_output=input.dtype.kind == 'c')
1607
+ axes = _ni_support._check_axes(axes, input.ndim)
1608
+ num_axes = len(axes)
1609
+ sizes = _ni_support._normalize_sequence(size, num_axes)
1610
+ origins = _ni_support._normalize_sequence(origin, num_axes)
1611
+ modes = _ni_support._normalize_sequence(mode, num_axes)
1612
+ axes = [(axes[ii], sizes[ii], origins[ii], modes[ii])
1613
+ for ii in range(num_axes) if sizes[ii] > 1]
1614
+ if len(axes) > 0:
1615
+ for axis, size, origin, mode in axes:
1616
+ uniform_filter1d(input, int(size), axis, output, mode,
1617
+ cval, origin)
1618
+ input = output
1619
+ else:
1620
+ output[...] = input[...]
1621
+ return output
1622
+
1623
+
1624
+ @_ni_docstrings.docfiller
1625
+ def minimum_filter1d(input, size, axis=-1, output=None,
1626
+ mode="reflect", cval=0.0, origin=0):
1627
+ """Calculate a 1-D minimum filter along the given axis.
1628
+
1629
+ The lines of the array along the given axis are filtered with a
1630
+ minimum filter of given size.
1631
+
1632
+ Parameters
1633
+ ----------
1634
+ %(input)s
1635
+ size : int
1636
+ length along which to calculate 1D minimum
1637
+ %(axis)s
1638
+ %(output)s
1639
+ %(mode_reflect)s
1640
+ %(cval)s
1641
+ %(origin)s
1642
+
1643
+ Returns
1644
+ -------
1645
+ result : ndarray.
1646
+ Filtered image. Has the same shape as `input`.
1647
+
1648
+ Notes
1649
+ -----
1650
+ This function implements the MINLIST algorithm [1]_, as described by
1651
+ Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being
1652
+ the `input` length, regardless of filter size.
1653
+
1654
+ References
1655
+ ----------
1656
+ .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777.
1657
+ .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html
1658
+
1659
+
1660
+ Examples
1661
+ --------
1662
+ >>> from scipy.ndimage import minimum_filter1d
1663
+ >>> minimum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
1664
+ array([2, 0, 0, 0, 1, 1, 0, 0])
1665
+ """
1666
+ input = np.asarray(input)
1667
+ if np.iscomplexobj(input):
1668
+ raise TypeError('Complex type not supported')
1669
+ axis = normalize_axis_index(axis, input.ndim)
1670
+ if size < 1:
1671
+ raise RuntimeError('incorrect filter size')
1672
+ output = _ni_support._get_output(output, input)
1673
+ if (size // 2 + origin < 0) or (size // 2 + origin >= size):
1674
+ raise ValueError('invalid origin')
1675
+ mode = _ni_support._extend_mode_to_code(mode)
1676
+ _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,
1677
+ origin, 1)
1678
+ return output
1679
+
1680
+
1681
+ @_ni_docstrings.docfiller
1682
+ def maximum_filter1d(input, size, axis=-1, output=None,
1683
+ mode="reflect", cval=0.0, origin=0):
1684
+ """Calculate a 1-D maximum filter along the given axis.
1685
+
1686
+ The lines of the array along the given axis are filtered with a
1687
+ maximum filter of given size.
1688
+
1689
+ Parameters
1690
+ ----------
1691
+ %(input)s
1692
+ size : int
1693
+ Length along which to calculate the 1-D maximum.
1694
+ %(axis)s
1695
+ %(output)s
1696
+ %(mode_reflect)s
1697
+ %(cval)s
1698
+ %(origin)s
1699
+
1700
+ Returns
1701
+ -------
1702
+ maximum1d : ndarray, None
1703
+ Maximum-filtered array with same shape as input.
1704
+ None if `output` is not None
1705
+
1706
+ Notes
1707
+ -----
1708
+ This function implements the MAXLIST algorithm [1]_, as described by
1709
+ Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being
1710
+ the `input` length, regardless of filter size.
1711
+
1712
+ References
1713
+ ----------
1714
+ .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777.
1715
+ .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html
1716
+
1717
+ Examples
1718
+ --------
1719
+ >>> from scipy.ndimage import maximum_filter1d
1720
+ >>> maximum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
1721
+ array([8, 8, 8, 4, 9, 9, 9, 9])
1722
+ """
1723
+ input = np.asarray(input)
1724
+ if np.iscomplexobj(input):
1725
+ raise TypeError('Complex type not supported')
1726
+ axis = normalize_axis_index(axis, input.ndim)
1727
+ if size < 1:
1728
+ raise RuntimeError('incorrect filter size')
1729
+ output = _ni_support._get_output(output, input)
1730
+ if (size // 2 + origin < 0) or (size // 2 + origin >= size):
1731
+ raise ValueError('invalid origin')
1732
+ mode = _ni_support._extend_mode_to_code(mode)
1733
+ _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,
1734
+ origin, 0)
1735
+ return output
1736
+
1737
+
1738
+ def _min_or_max_filter(input, size, footprint, structure, output, mode,
1739
+ cval, origin, minimum, axes=None):
1740
+ if (size is not None) and (footprint is not None):
1741
+ warnings.warn("ignoring size because footprint is set",
1742
+ UserWarning, stacklevel=3)
1743
+ if structure is None:
1744
+ if footprint is None:
1745
+ if size is None:
1746
+ raise RuntimeError("no footprint provided")
1747
+ separable = True
1748
+ else:
1749
+ footprint = np.asarray(footprint, dtype=bool)
1750
+ if not footprint.any():
1751
+ raise ValueError("All-zero footprint is not supported.")
1752
+ if footprint.all():
1753
+ size = footprint.shape
1754
+ footprint = None
1755
+ separable = True
1756
+ else:
1757
+ separable = False
1758
+ else:
1759
+ structure = np.asarray(structure, dtype=np.float64)
1760
+ separable = False
1761
+ if footprint is None:
1762
+ footprint = np.ones(structure.shape, bool)
1763
+ else:
1764
+ footprint = np.asarray(footprint, dtype=bool)
1765
+ input = np.asarray(input)
1766
+ if np.iscomplexobj(input):
1767
+ raise TypeError("Complex type not supported")
1768
+ output = _ni_support._get_output(output, input)
1769
+ temp_needed = np.may_share_memory(input, output)
1770
+ if temp_needed:
1771
+ # input and output arrays cannot share memory
1772
+ temp = output
1773
+ output = _ni_support._get_output(output.dtype, input)
1774
+ axes = _ni_support._check_axes(axes, input.ndim)
1775
+ num_axes = len(axes)
1776
+ if separable:
1777
+ origins = _ni_support._normalize_sequence(origin, num_axes)
1778
+ sizes = _ni_support._normalize_sequence(size, num_axes)
1779
+ modes = _ni_support._normalize_sequence(mode, num_axes)
1780
+ axes = [(axes[ii], sizes[ii], origins[ii], modes[ii])
1781
+ for ii in range(len(axes)) if sizes[ii] > 1]
1782
+ if minimum:
1783
+ filter_ = minimum_filter1d
1784
+ else:
1785
+ filter_ = maximum_filter1d
1786
+ if len(axes) > 0:
1787
+ for axis, size, origin, mode in axes:
1788
+ filter_(input, int(size), axis, output, mode, cval, origin)
1789
+ input = output
1790
+ else:
1791
+ output[...] = input[...]
1792
+ else:
1793
+ # expand origins and footprint if num_axes < input.ndim
1794
+ footprint = _expand_footprint(input.ndim, axes, footprint)
1795
+ origins = _expand_origin(input.ndim, axes, origin)
1796
+
1797
+ fshape = [ii for ii in footprint.shape if ii > 0]
1798
+ if len(fshape) != input.ndim:
1799
+ raise RuntimeError(f"footprint.ndim ({footprint.ndim}) must match "
1800
+ f"len(axes) ({len(axes)})")
1801
+ for origin, lenf in zip(origins, fshape):
1802
+ if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
1803
+ raise ValueError("invalid origin")
1804
+ if not footprint.flags.contiguous:
1805
+ footprint = footprint.copy()
1806
+ if structure is not None:
1807
+ if len(structure.shape) != num_axes:
1808
+ raise RuntimeError("structure array has incorrect shape")
1809
+ if num_axes != structure.ndim:
1810
+ structure = np.expand_dims(
1811
+ structure,
1812
+ tuple(ax for ax in range(structure.ndim) if ax not in axes)
1813
+ )
1814
+ if not structure.flags.contiguous:
1815
+ structure = structure.copy()
1816
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
1817
+ raise RuntimeError(
1818
+ "A sequence of modes is not supported for non-separable "
1819
+ "footprints")
1820
+ mode = _ni_support._extend_mode_to_code(mode)
1821
+ _nd_image.min_or_max_filter(input, footprint, structure, output,
1822
+ mode, cval, origins, minimum)
1823
+ if temp_needed:
1824
+ temp[...] = output
1825
+ output = temp
1826
+ return output
1827
+
1828
+
1829
+ @_ni_docstrings.docfiller
1830
+ def minimum_filter(input, size=None, footprint=None, output=None,
1831
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
1832
+ """Calculate a multidimensional minimum filter.
1833
+
1834
+ Parameters
1835
+ ----------
1836
+ %(input)s
1837
+ %(size_foot)s
1838
+ %(output)s
1839
+ %(mode_multiple)s
1840
+ %(cval)s
1841
+ %(origin_multiple)s
1842
+ axes : tuple of int or None, optional
1843
+ If None, `input` is filtered along all axes. Otherwise,
1844
+ `input` is filtered along the specified axes. When `axes` is
1845
+ specified, any tuples used for `size`, `origin`, and/or `mode`
1846
+ must match the length of `axes`. The ith entry in any of these tuples
1847
+ corresponds to the ith entry in `axes`.
1848
+
1849
+ Returns
1850
+ -------
1851
+ minimum_filter : ndarray
1852
+ Filtered array. Has the same shape as `input`.
1853
+
1854
+ Notes
1855
+ -----
1856
+ A sequence of modes (one per axis) is only supported when the footprint is
1857
+ separable. Otherwise, a single mode string must be provided.
1858
+
1859
+ Examples
1860
+ --------
1861
+ >>> from scipy import ndimage, datasets
1862
+ >>> import matplotlib.pyplot as plt
1863
+ >>> fig = plt.figure()
1864
+ >>> plt.gray() # show the filtered result in grayscale
1865
+ >>> ax1 = fig.add_subplot(121) # left side
1866
+ >>> ax2 = fig.add_subplot(122) # right side
1867
+ >>> ascent = datasets.ascent()
1868
+ >>> result = ndimage.minimum_filter(ascent, size=20)
1869
+ >>> ax1.imshow(ascent)
1870
+ >>> ax2.imshow(result)
1871
+ >>> plt.show()
1872
+ """
1873
+ return _min_or_max_filter(input, size, footprint, None, output, mode,
1874
+ cval, origin, 1, axes)
1875
+
1876
+
1877
+ @_ni_docstrings.docfiller
1878
+ def maximum_filter(input, size=None, footprint=None, output=None,
1879
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
1880
+ """Calculate a multidimensional maximum filter.
1881
+
1882
+ Parameters
1883
+ ----------
1884
+ %(input)s
1885
+ %(size_foot)s
1886
+ %(output)s
1887
+ %(mode_multiple)s
1888
+ %(cval)s
1889
+ %(origin_multiple)s
1890
+ axes : tuple of int or None, optional
1891
+ If None, `input` is filtered along all axes. Otherwise,
1892
+ `input` is filtered along the specified axes. When `axes` is
1893
+ specified, any tuples used for `size`, `origin`, and/or `mode`
1894
+ must match the length of `axes`. The ith entry in any of these tuples
1895
+ corresponds to the ith entry in `axes`.
1896
+
1897
+ Returns
1898
+ -------
1899
+ maximum_filter : ndarray
1900
+ Filtered array. Has the same shape as `input`.
1901
+
1902
+ Notes
1903
+ -----
1904
+ A sequence of modes (one per axis) is only supported when the footprint is
1905
+ separable. Otherwise, a single mode string must be provided.
1906
+
1907
+ %(nan)s
1908
+
1909
+ Examples
1910
+ --------
1911
+ >>> from scipy import ndimage, datasets
1912
+ >>> import matplotlib.pyplot as plt
1913
+ >>> fig = plt.figure()
1914
+ >>> plt.gray() # show the filtered result in grayscale
1915
+ >>> ax1 = fig.add_subplot(121) # left side
1916
+ >>> ax2 = fig.add_subplot(122) # right side
1917
+ >>> ascent = datasets.ascent()
1918
+ >>> result = ndimage.maximum_filter(ascent, size=20)
1919
+ >>> ax1.imshow(ascent)
1920
+ >>> ax2.imshow(result)
1921
+ >>> plt.show()
1922
+ """
1923
+ return _min_or_max_filter(input, size, footprint, None, output, mode,
1924
+ cval, origin, 0, axes)
1925
+
1926
+
1927
+ @_ni_docstrings.docfiller
1928
+ def _rank_filter(input, rank, size=None, footprint=None, output=None,
1929
+ mode="reflect", cval=0.0, origin=0, operation='rank',
1930
+ axes=None):
1931
+ if (size is not None) and (footprint is not None):
1932
+ warnings.warn("ignoring size because footprint is set",
1933
+ UserWarning, stacklevel=3)
1934
+ input = np.asarray(input)
1935
+ if np.iscomplexobj(input):
1936
+ raise TypeError('Complex type not supported')
1937
+ axes = _ni_support._check_axes(axes, input.ndim)
1938
+ num_axes = len(axes)
1939
+ if footprint is None:
1940
+ if size is None:
1941
+ raise RuntimeError("no footprint or filter size provided")
1942
+ sizes = _ni_support._normalize_sequence(size, num_axes)
1943
+ footprint = np.ones(sizes, dtype=bool)
1944
+ else:
1945
+ footprint = np.asarray(footprint, dtype=bool)
1946
+ # expand origins, footprint and modes if num_axes < input.ndim
1947
+ footprint = _expand_footprint(input.ndim, axes, footprint)
1948
+ origins = _expand_origin(input.ndim, axes, origin)
1949
+ mode = _expand_mode(input.ndim, axes, mode)
1950
+
1951
+ fshape = [ii for ii in footprint.shape if ii > 0]
1952
+ if len(fshape) != input.ndim:
1953
+ raise RuntimeError(f"footprint.ndim ({footprint.ndim}) must match "
1954
+ f"len(axes) ({len(axes)})")
1955
+ for origin, lenf in zip(origins, fshape):
1956
+ if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
1957
+ raise ValueError('invalid origin')
1958
+ if not footprint.flags.contiguous:
1959
+ footprint = footprint.copy()
1960
+ filter_size = np.where(footprint, 1, 0).sum()
1961
+ if operation == 'median':
1962
+ rank = filter_size // 2
1963
+ elif operation == 'percentile':
1964
+ percentile = rank
1965
+ if percentile < 0.0:
1966
+ percentile += 100.0
1967
+ if percentile < 0 or percentile > 100:
1968
+ raise RuntimeError('invalid percentile')
1969
+ if percentile == 100.0:
1970
+ rank = filter_size - 1
1971
+ else:
1972
+ rank = int(float(filter_size) * percentile / 100.0)
1973
+ if rank < 0:
1974
+ rank += filter_size
1975
+ if rank < 0 or rank >= filter_size:
1976
+ raise RuntimeError('rank not within filter footprint size')
1977
+ if rank == 0:
1978
+ return minimum_filter(input, None, footprint, output, mode, cval,
1979
+ origins, axes=None)
1980
+ elif rank == filter_size - 1:
1981
+ return maximum_filter(input, None, footprint, output, mode, cval,
1982
+ origins, axes=None)
1983
+ else:
1984
+ output = _ni_support._get_output(output, input)
1985
+ temp_needed = np.may_share_memory(input, output)
1986
+ if temp_needed:
1987
+ # input and output arrays cannot share memory
1988
+ temp = output
1989
+ output = _ni_support._get_output(output.dtype, input)
1990
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
1991
+ raise RuntimeError(
1992
+ "A sequence of modes is not supported by non-separable rank "
1993
+ "filters")
1994
+ mode = _ni_support._extend_mode_to_code(mode, is_filter=True)
1995
+ # Some corner cases are currently not allowed to use the
1996
+ # "new"/fast 1D rank filter code, including when the
1997
+ # footprint is large compared to the array size.
1998
+ # See discussion in gh-23293; longer-term it may be possible
1999
+ # to allow the fast path for these corner cases as well,
2000
+ # if algorithmic fixes are found.
2001
+ lim2 = input.size - ((footprint.size - 1) // 2 - origin)
2002
+ if input.ndim == 1 and ((lim2 >= 0) or (input.size == 1)):
2003
+ if input.dtype in (np.int64, np.float64, np.float32):
2004
+ x = input
2005
+ x_out = output
2006
+ elif input.dtype == np.float16:
2007
+ x = input.astype('float32')
2008
+ x_out = np.empty(x.shape, dtype='float32')
2009
+ elif np.result_type(input, np.int64) == np.int64:
2010
+ x = input.astype('int64')
2011
+ x_out = np.empty(x.shape, dtype='int64')
2012
+ elif input.dtype.kind in 'biu':
2013
+ # cast any other boolean, integer or unsigned type to int64
2014
+ x = input.astype('int64')
2015
+ x_out = np.empty(x.shape, dtype='int64')
2016
+ else:
2017
+ raise RuntimeError('Unsupported array type')
2018
+ cval = x.dtype.type(cval)
2019
+ _rank_filter_1d.rank_filter(x, rank, footprint.size, x_out, mode, cval,
2020
+ origin)
2021
+ if input.dtype not in (np.int64, np.float64, np.float32):
2022
+ np.copyto(output, x_out, casting='unsafe')
2023
+ else:
2024
+ _nd_image.rank_filter(input, rank, footprint, output, mode, cval, origins)
2025
+ if temp_needed:
2026
+ temp[...] = output
2027
+ output = temp
2028
+ return output
2029
+
2030
+
2031
+ @_ni_docstrings.docfiller
2032
+ def rank_filter(input, rank, size=None, footprint=None, output=None,
2033
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
2034
+ """Calculate a multidimensional rank filter.
2035
+
2036
+ Parameters
2037
+ ----------
2038
+ %(input)s
2039
+ rank : int
2040
+ The rank parameter may be less than zero, i.e., rank = -1
2041
+ indicates the largest element.
2042
+ %(size_foot)s
2043
+ %(output)s
2044
+ %(mode_reflect)s
2045
+ %(cval)s
2046
+ %(origin_multiple)s
2047
+ axes : tuple of int or None, optional
2048
+ If None, `input` is filtered along all axes. Otherwise,
2049
+ `input` is filtered along the specified axes. When `axes` is
2050
+ specified, any tuples used for `size`, `origin`, and/or `mode`
2051
+ must match the length of `axes`. The ith entry in any of these tuples
2052
+ corresponds to the ith entry in `axes`.
2053
+
2054
+ Returns
2055
+ -------
2056
+ rank_filter : ndarray
2057
+ Filtered array. Has the same shape as `input`.
2058
+
2059
+ Examples
2060
+ --------
2061
+ >>> from scipy import ndimage, datasets
2062
+ >>> import matplotlib.pyplot as plt
2063
+ >>> fig = plt.figure()
2064
+ >>> plt.gray() # show the filtered result in grayscale
2065
+ >>> ax1 = fig.add_subplot(121) # left side
2066
+ >>> ax2 = fig.add_subplot(122) # right side
2067
+ >>> ascent = datasets.ascent()
2068
+ >>> result = ndimage.rank_filter(ascent, rank=42, size=20)
2069
+ >>> ax1.imshow(ascent)
2070
+ >>> ax2.imshow(result)
2071
+ >>> plt.show()
2072
+ """
2073
+ rank = operator.index(rank)
2074
+ return _rank_filter(input, rank, size, footprint, output, mode, cval,
2075
+ origin, 'rank', axes=axes)
2076
+
2077
+
2078
+ @_ni_docstrings.docfiller
2079
+ def median_filter(input, size=None, footprint=None, output=None,
2080
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
2081
+ """
2082
+ Calculate a multidimensional median filter.
2083
+
2084
+ Parameters
2085
+ ----------
2086
+ %(input)s
2087
+ %(size_foot)s
2088
+ %(output)s
2089
+ %(mode_reflect)s
2090
+ %(cval)s
2091
+ %(origin_multiple)s
2092
+ axes : tuple of int or None, optional
2093
+ If None, `input` is filtered along all axes. Otherwise,
2094
+ `input` is filtered along the specified axes. When `axes` is
2095
+ specified, any tuples used for `size`, `origin`, and/or `mode`
2096
+ must match the length of `axes`. The ith entry in any of these tuples
2097
+ corresponds to the ith entry in `axes`.
2098
+
2099
+ Returns
2100
+ -------
2101
+ median_filter : ndarray
2102
+ Filtered array. Has the same shape as `input`.
2103
+
2104
+ See Also
2105
+ --------
2106
+ scipy.signal.medfilt2d
2107
+
2108
+ Notes
2109
+ -----
2110
+ For 2-dimensional images with ``uint8``, ``float32`` or ``float64`` dtypes
2111
+ the specialised function `scipy.signal.medfilt2d` may be faster. It is
2112
+ however limited to constant mode with ``cval=0``.
2113
+
2114
+ The filter always returns the argument that would appear at index ``n // 2`` in
2115
+ a sorted array, where ``n`` is the number of elements in the footprint of the
2116
+ filter. Note that this differs from the conventional definition of the median
2117
+ when ``n`` is even. Also, this function does not support the ``float16`` dtype,
2118
+ behavior in the presence of NaNs is undefined, and memory consumption scales with
2119
+ ``n**4``. For ``float16`` support, greater control over the definition of the
2120
+ filter, and to limit memory usage, consider using `vectorized_filter` with
2121
+ NumPy functions `np.median` or `np.nanmedian`.
2122
+
2123
+ Examples
2124
+ --------
2125
+ >>> from scipy import ndimage, datasets
2126
+ >>> import matplotlib.pyplot as plt
2127
+ >>> fig = plt.figure()
2128
+ >>> plt.gray() # show the filtered result in grayscale
2129
+ >>> ax1 = fig.add_subplot(121) # left side
2130
+ >>> ax2 = fig.add_subplot(122) # right side
2131
+ >>> ascent = datasets.ascent()
2132
+ >>> result = ndimage.median_filter(ascent, size=20)
2133
+ >>> ax1.imshow(ascent)
2134
+ >>> ax2.imshow(result)
2135
+ >>> plt.show()
2136
+ """
2137
+ return _rank_filter(input, 0, size, footprint, output, mode, cval,
2138
+ origin, 'median', axes=axes)
2139
+
2140
+
2141
+ @_ni_docstrings.docfiller
2142
+ def percentile_filter(input, percentile, size=None, footprint=None,
2143
+ output=None, mode="reflect", cval=0.0, origin=0, *,
2144
+ axes=None):
2145
+ """Calculate a multidimensional percentile filter.
2146
+
2147
+ Parameters
2148
+ ----------
2149
+ %(input)s
2150
+ percentile : scalar
2151
+ The percentile parameter may be less than zero, i.e.,
2152
+ percentile = -20 equals percentile = 80
2153
+ %(size_foot)s
2154
+ %(output)s
2155
+ %(mode_reflect)s
2156
+ %(cval)s
2157
+ %(origin_multiple)s
2158
+ axes : tuple of int or None, optional
2159
+ If None, `input` is filtered along all axes. Otherwise,
2160
+ `input` is filtered along the specified axes. When `axes` is
2161
+ specified, any tuples used for `size`, `origin`, and/or `mode`
2162
+ must match the length of `axes`. The ith entry in any of these tuples
2163
+ corresponds to the ith entry in `axes`.
2164
+
2165
+ Returns
2166
+ -------
2167
+ percentile_filter : ndarray
2168
+ Filtered array. Has the same shape as `input`.
2169
+
2170
+ Examples
2171
+ --------
2172
+ >>> from scipy import ndimage, datasets
2173
+ >>> import matplotlib.pyplot as plt
2174
+ >>> fig = plt.figure()
2175
+ >>> plt.gray() # show the filtered result in grayscale
2176
+ >>> ax1 = fig.add_subplot(121) # left side
2177
+ >>> ax2 = fig.add_subplot(122) # right side
2178
+ >>> ascent = datasets.ascent()
2179
+ >>> result = ndimage.percentile_filter(ascent, percentile=20, size=20)
2180
+ >>> ax1.imshow(ascent)
2181
+ >>> ax2.imshow(result)
2182
+ >>> plt.show()
2183
+ """
2184
+ return _rank_filter(input, percentile, size, footprint, output, mode,
2185
+ cval, origin, 'percentile', axes=axes)
2186
+
2187
+
2188
+ @_ni_docstrings.docfiller
2189
+ def generic_filter1d(input, function, filter_size, axis=-1,
2190
+ output=None, mode="reflect", cval=0.0, origin=0,
2191
+ extra_arguments=(), extra_keywords=None):
2192
+ """Calculate a 1-D filter along the given axis.
2193
+
2194
+ `generic_filter1d` iterates over the lines of the array, calling the
2195
+ given function at each line. The arguments of the line are the
2196
+ input line, and the output line. The input and output lines are 1-D
2197
+ double arrays. The input line is extended appropriately according
2198
+ to the filter size and origin. The output line must be modified
2199
+ in-place with the result.
2200
+
2201
+ Parameters
2202
+ ----------
2203
+ %(input)s
2204
+ function : {callable, scipy.LowLevelCallable}
2205
+ Function to apply along given axis.
2206
+ filter_size : scalar
2207
+ Length of the filter.
2208
+ %(axis)s
2209
+ %(output)s
2210
+ %(mode_reflect)s
2211
+ %(cval)s
2212
+ %(origin)s
2213
+ %(extra_arguments)s
2214
+ %(extra_keywords)s
2215
+
2216
+ Returns
2217
+ -------
2218
+ generic_filter1d : ndarray
2219
+ Filtered array. Has the same shape as `input`.
2220
+
2221
+ Notes
2222
+ -----
2223
+ This function also accepts low-level callback functions with one of
2224
+ the following signatures and wrapped in `scipy.LowLevelCallable`:
2225
+
2226
+ .. code:: c
2227
+
2228
+ int function(double *input_line, npy_intp input_length,
2229
+ double *output_line, npy_intp output_length,
2230
+ void *user_data)
2231
+ int function(double *input_line, intptr_t input_length,
2232
+ double *output_line, intptr_t output_length,
2233
+ void *user_data)
2234
+
2235
+ The calling function iterates over the lines of the input and output
2236
+ arrays, calling the callback function at each line. The current line
2237
+ is extended according to the border conditions set by the calling
2238
+ function, and the result is copied into the array that is passed
2239
+ through ``input_line``. The length of the input line (after extension)
2240
+ is passed through ``input_length``. The callback function should apply
2241
+ the filter and store the result in the array passed through
2242
+ ``output_line``. The length of the output line is passed through
2243
+ ``output_length``. ``user_data`` is the data pointer provided
2244
+ to `scipy.LowLevelCallable` as-is.
2245
+
2246
+ The callback function must return an integer error status that is zero
2247
+ if something went wrong and one otherwise. If an error occurs, you should
2248
+ normally set the python error status with an informative message
2249
+ before returning, otherwise a default error message is set by the
2250
+ calling function.
2251
+
2252
+ In addition, some other low-level function pointer specifications
2253
+ are accepted, but these are for backward compatibility only and should
2254
+ not be used in new code.
2255
+
2256
+ Examples
2257
+ --------
2258
+ This example defines and applies a custom callback function that computes
2259
+ the range (maximum minus minimum) within a sliding window of size 3.
2260
+ It utilizes `numpy.lib.stride_tricks.sliding_window_view` and demonstrates the
2261
+ required in-place modification of the ``output_line`` array.
2262
+
2263
+ >>> import numpy as np
2264
+ >>> from scipy.ndimage import generic_filter1d
2265
+ >>> from numpy.lib.stride_tricks import sliding_window_view
2266
+
2267
+ >>> def local_range(input_line, output_line):
2268
+ ... # input_line includes padded values according to `filter_size` and `mode`
2269
+ ... v = sliding_window_view(input_line, 3)
2270
+ ... # modify `output_line` in-place rather than returning the result
2271
+ ... output_line[:] = v.max(axis=1) - v.min(axis=1)
2272
+
2273
+ >>> x = np.array([1, 2, 3, 4, 5], dtype=np.float64)
2274
+ >>> generic_filter1d(x, local_range, filter_size=3)
2275
+ array([1., 2., 2., 2., 1.])
2276
+
2277
+ """
2278
+ if extra_keywords is None:
2279
+ extra_keywords = {}
2280
+ input = np.asarray(input)
2281
+ if np.iscomplexobj(input):
2282
+ raise TypeError('Complex type not supported')
2283
+ output = _ni_support._get_output(output, input)
2284
+ if filter_size < 1:
2285
+ raise RuntimeError('invalid filter size')
2286
+ axis = normalize_axis_index(axis, input.ndim)
2287
+ if (filter_size // 2 + origin < 0) or (filter_size // 2 + origin >=
2288
+ filter_size):
2289
+ raise ValueError('invalid origin')
2290
+ mode = _ni_support._extend_mode_to_code(mode)
2291
+ _nd_image.generic_filter1d(input, function, filter_size, axis, output,
2292
+ mode, cval, origin, extra_arguments,
2293
+ extra_keywords)
2294
+ return output
2295
+
2296
+
2297
+ @_ni_docstrings.docfiller
2298
+ def generic_filter(input, function, size=None, footprint=None,
2299
+ output=None, mode="reflect", cval=0.0, origin=0,
2300
+ extra_arguments=(), extra_keywords=None, *, axes=None):
2301
+ """Calculate a multidimensional filter using the given function.
2302
+
2303
+ At each element the provided function is called. The input values
2304
+ within the filter footprint at that element are passed to the function
2305
+ as a 1-D array of double values.
2306
+
2307
+ Parameters
2308
+ ----------
2309
+ %(input)s
2310
+ function : {callable, scipy.LowLevelCallable}
2311
+ Function to apply at each element.
2312
+ %(size_foot)s
2313
+ %(output)s
2314
+ %(mode_reflect)s
2315
+ %(cval)s
2316
+ %(origin_multiple)s
2317
+ %(extra_arguments)s
2318
+ %(extra_keywords)s
2319
+ axes : tuple of int or None, optional
2320
+ If None, `input` is filtered along all axes. Otherwise,
2321
+ `input` is filtered along the specified axes. When `axes` is
2322
+ specified, any tuples used for `size` or `origin` must match the length
2323
+ of `axes`. The ith entry in any of these tuples corresponds to the ith
2324
+ entry in `axes`.
2325
+
2326
+ Returns
2327
+ -------
2328
+ output : ndarray
2329
+ Filtered array. Has the same shape as `input`.
2330
+
2331
+ See Also
2332
+ --------
2333
+ vectorized_filter : similar functionality, but optimized for vectorized callables
2334
+
2335
+ Notes
2336
+ -----
2337
+ This function is ideal for use with instances of `scipy.LowLevelCallable`;
2338
+ for vectorized, pure-Python callables, consider `vectorized_filter` for improved
2339
+ performance.
2340
+
2341
+ Low-level callback functions must have one of the following signatures:
2342
+
2343
+ .. code:: c
2344
+
2345
+ int callback(double *buffer, npy_intp filter_size,
2346
+ double *return_value, void *user_data)
2347
+ int callback(double *buffer, intptr_t filter_size,
2348
+ double *return_value, void *user_data)
2349
+
2350
+ The calling function iterates over the elements of the input and
2351
+ output arrays, calling the callback function at each element. The
2352
+ elements within the footprint of the filter at the current element are
2353
+ passed through the ``buffer`` parameter, and the number of elements
2354
+ within the footprint through ``filter_size``. The calculated value is
2355
+ returned in ``return_value``. ``user_data`` is the data pointer provided
2356
+ to `scipy.LowLevelCallable` as-is.
2357
+
2358
+ The callback function must return an integer error status that is zero
2359
+ if something went wrong and one otherwise. If an error occurs, you should
2360
+ normally set the python error status with an informative message
2361
+ before returning, otherwise a default error message is set by the
2362
+ calling function.
2363
+
2364
+ In addition, some other low-level function pointer specifications
2365
+ are accepted, but these are for backward compatibility only and should
2366
+ not be used in new code.
2367
+
2368
+ Examples
2369
+ --------
2370
+ Import the necessary modules and load the example image used for
2371
+ filtering.
2372
+
2373
+ >>> import numpy as np
2374
+ >>> from scipy import datasets
2375
+ >>> from scipy.ndimage import zoom, generic_filter
2376
+ >>> import matplotlib.pyplot as plt
2377
+ >>> ascent = zoom(datasets.ascent(), 0.5)
2378
+
2379
+ Compute a maximum filter with kernel size 5 by passing a simple NumPy
2380
+ aggregation function as argument to `function`.
2381
+
2382
+ >>> maximum_filter_result = generic_filter(ascent, np.amax, [5, 5])
2383
+
2384
+ While a maximum filter could also directly be obtained using
2385
+ `maximum_filter`, `generic_filter` allows generic Python function or
2386
+ `scipy.LowLevelCallable` to be used as a filter. Here, we compute the
2387
+ range between maximum and minimum value as an example for a kernel size
2388
+ of 5.
2389
+
2390
+ >>> def custom_filter(image):
2391
+ ... return np.amax(image) - np.amin(image)
2392
+ >>> custom_filter_result = generic_filter(ascent, custom_filter, [5, 5])
2393
+
2394
+ Plot the original and filtered images.
2395
+
2396
+ >>> fig, axes = plt.subplots(3, 1, figsize=(3, 9))
2397
+ >>> plt.gray() # show the filtered result in grayscale
2398
+ >>> top, middle, bottom = axes
2399
+ >>> for ax in axes:
2400
+ ... ax.set_axis_off() # remove coordinate system
2401
+ >>> top.imshow(ascent)
2402
+ >>> top.set_title("Original image")
2403
+ >>> middle.imshow(maximum_filter_result)
2404
+ >>> middle.set_title("Maximum filter, Kernel: 5x5")
2405
+ >>> bottom.imshow(custom_filter_result)
2406
+ >>> bottom.set_title("Custom filter, Kernel: 5x5")
2407
+ >>> fig.tight_layout()
2408
+
2409
+ """
2410
+ if (size is not None) and (footprint is not None):
2411
+ warnings.warn("ignoring size because footprint is set",
2412
+ UserWarning, stacklevel=2)
2413
+ if extra_keywords is None:
2414
+ extra_keywords = {}
2415
+ input = np.asarray(input)
2416
+ if np.iscomplexobj(input):
2417
+ raise TypeError('Complex type not supported')
2418
+ axes = _ni_support._check_axes(axes, input.ndim)
2419
+ num_axes = len(axes)
2420
+ if footprint is None:
2421
+ if size is None:
2422
+ raise RuntimeError("no footprint or filter size provided")
2423
+ sizes = _ni_support._normalize_sequence(size, num_axes)
2424
+ footprint = np.ones(sizes, dtype=bool)
2425
+ else:
2426
+ footprint = np.asarray(footprint, dtype=bool)
2427
+
2428
+ # expand origins, footprint if num_axes < input.ndim
2429
+ footprint = _expand_footprint(input.ndim, axes, footprint)
2430
+ origins = _expand_origin(input.ndim, axes, origin)
2431
+
2432
+ fshape = [ii for ii in footprint.shape if ii > 0]
2433
+ if len(fshape) != input.ndim:
2434
+ raise RuntimeError(f"footprint.ndim ({footprint.ndim}) "
2435
+ f"must match len(axes) ({num_axes})")
2436
+ for origin, lenf in zip(origins, fshape):
2437
+ if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
2438
+ raise ValueError('invalid origin')
2439
+ if not footprint.flags.contiguous:
2440
+ footprint = footprint.copy()
2441
+ output = _ni_support._get_output(output, input)
2442
+
2443
+ mode = _ni_support._extend_mode_to_code(mode)
2444
+ _nd_image.generic_filter(input, function, footprint, output, mode,
2445
+ cval, origins, extra_arguments, extra_keywords)
2446
+ return output
.venv/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/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._external 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/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 an 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
+ """ # numpydoc ignore=RT01
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/lib/python3.12/site-packages/scipy/ndimage/_morphology.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:100424b75cdc0e0d0a42ef8a9df2f205597706c3567100bfe929f246b2a33df0
3
+ size 175576
.venv/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/lib/python3.12/site-packages/scipy/ndimage/_ni_docstrings.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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' (`b c d b c | a b c d | b c a b c`)
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
+
118
+
119
+ For the example illustrated above, the edge values ``a`` and ``d`` overlap,
120
+ while the inner pattern ``b c`` repeats. The example demonstrates one
121
+ possible output, while ``b c a b c | a b c d | b c d b c`` is another,
122
+ since either ``a`` or ``d`` may occur at each point of overlap.""")
123
+ _mode_interp_mirror_doc = (
124
+ _mode_interp_constant_doc.replace("Default is 'constant'",
125
+ "Default is 'mirror'")
126
+ )
127
+ assert _mode_interp_mirror_doc != _mode_interp_constant_doc, \
128
+ 'Default not replaced'
129
+
130
+ _mode_multiple_doc = (
131
+ """mode : str or sequence, optional
132
+ The `mode` parameter determines how the input array is extended
133
+ when the filter overlaps a border. By passing a sequence of modes
134
+ with length equal to the number of dimensions of the input array,
135
+ different modes can be specified along each axis. Default value is
136
+ 'reflect'. The valid values and their behavior is as follows:
137
+
138
+ 'reflect' (`d c b a | a b c d | d c b a`)
139
+ The input is extended by reflecting about the edge of the last
140
+ pixel. This mode is also sometimes referred to as half-sample
141
+ symmetric.
142
+
143
+ 'constant' (`k k k k | a b c d | k k k k`)
144
+ The input is extended by filling all values beyond the edge with
145
+ the same constant value, defined by the `cval` parameter.
146
+
147
+ 'nearest' (`a a a a | a b c d | d d d d`)
148
+ The input is extended by replicating the last pixel.
149
+
150
+ 'mirror' (`d c b | a b c d | c b a`)
151
+ The input is extended by reflecting about the center of the last
152
+ pixel. This mode is also sometimes referred to as whole-sample
153
+ symmetric.
154
+
155
+ 'wrap' (`a b c d | a b c d | a b c d`)
156
+ The input is extended by wrapping around to the opposite edge.
157
+
158
+ For consistency with the interpolation functions, the following mode
159
+ names can also be used:
160
+
161
+ 'grid-constant'
162
+ This is a synonym for 'constant'.
163
+
164
+ 'grid-mirror'
165
+ This is a synonym for 'reflect'.
166
+
167
+ 'grid-wrap'
168
+ This is a synonym for 'wrap'.""")
169
+ _cval_doc = (
170
+ """cval : scalar, optional
171
+ Value to fill past edges of input if `mode` is 'constant'. Default
172
+ is 0.0.""")
173
+ _origin_doc = (
174
+ """origin : int, 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.""")
179
+ _origin_multiple_doc = (
180
+ """origin : int or sequence, optional
181
+ Controls the placement of the filter on the input array's pixels.
182
+ A value of 0 (the default) centers the filter over the pixel, with
183
+ positive values shifting the filter to the left, and negative ones
184
+ to the right. By passing a sequence of origins with length equal to
185
+ the number of dimensions of the input array, different shifts can
186
+ be specified along each axis.""")
187
+ _extra_arguments_doc = (
188
+ """extra_arguments : sequence, optional
189
+ Sequence of extra positional arguments to pass to passed function.""")
190
+ _extra_keywords_doc = (
191
+ """extra_keywords : dict, optional
192
+ dict of extra keyword arguments to pass to passed function.""")
193
+ _prefilter_doc = (
194
+ """prefilter : bool, optional
195
+ Determines if the input array is prefiltered with `spline_filter`
196
+ before interpolation. The default is True, which will create a
197
+ temporary `float64` array of filtered values if ``order > 1``. If
198
+ setting this to False, the output will be slightly blurred if
199
+ ``order > 1``, unless the input is prefiltered, i.e. it is the result
200
+ of calling `spline_filter` on the original input.""")
201
+
202
+ docdict = {
203
+ 'input': _input_doc,
204
+ 'axis': _axis_doc,
205
+ 'output': _output_doc,
206
+ 'size_foot': _size_foot_doc,
207
+ 'mode_interp_constant': _mode_interp_constant_doc,
208
+ 'mode_interp_mirror': _mode_interp_mirror_doc,
209
+ 'mode_reflect': _mode_reflect_doc,
210
+ 'mode_multiple': _mode_multiple_doc,
211
+ 'cval': _cval_doc,
212
+ 'origin': _origin_doc,
213
+ 'origin_multiple': _origin_multiple_doc,
214
+ 'extra_arguments': _extra_arguments_doc,
215
+ 'extra_keywords': _extra_keywords_doc,
216
+ 'prefilter': _prefilter_doc,
217
+ 'nan': _nan_doc,
218
+ }
219
+
220
+ docfiller: Final = doccer.filldoc(docdict)
.venv/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:639e113aee21ad4d53663fa9023f66aaff72c9706ed093aaf2f18c8cde8e4908
3
+ size 228496
.venv/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/lib/python3.12/site-packages/scipy/ndimage/_rank_filter_1d.cpython-312-x86_64-linux-gnu.so ADDED
Binary file (27 kB). View file
 
.venv/lib/python3.12/site-packages/scipy/ndimage/_support_alternative_backends.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "labeled_comprehension": xp_capabilities(np_only=True),
107
+ }
108
+
109
+ # ### decorate ###
110
+ for func_name in _ndimage_api.__all__:
111
+ bare_func = getattr(_ndimage_api, func_name)
112
+ delegator = getattr(_delegators, func_name + "_signature")
113
+
114
+ capabilities = capabilities_dict.get(func_name, default_capabilities)
115
+
116
+ # pyrefly:ignore[not-callable]
117
+ f = capabilities(
118
+ delegate_xp(delegator, MODULE_NAME)(bare_func)
119
+ if SCIPY_ARRAY_API else bare_func
120
+ )
121
+ # add the decorated function to the namespace, to be imported in __init__.py
122
+ vars()[func_name] = f
.venv/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/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)